Angular 2如何从innerHTML执行脚本标记 [英] Angular 2 how to execute script tag from innerHTML

查看:202
本文介绍了Angular 2如何从innerHTML执行脚本标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过 http.get()方法加载了 HTML 页面,并且我将此页面的内容添加到div标签。

I have load the HTML page by http.get() method, and i add content this page to div tag.

getRequestToAssignPage (param: string) : any {

    return this.$http.get(param)
        .map((res: Response) => {

            this.status = res;

            return res.text();
        })
        .toPromise()
        .then(response => {



            let restr: string = response;



            restr = restr.replace(/(<head[^>]*)(?:[^])*?\/head>/ig, '')
                .replace(/(<(\/?)body([^>]*?)>)/g, '')
                .replace(/(<style[^>]*)(?:[^])*?\/style>/g, '')
                .replace(/(<(\/?)html([^>]*?)>)/g, '')
                .replace(/(<app-root[^>]*)(?:[^])*?\/app-root>/ig, '')
                .replace(/(<\?[\s\S]*?\?>)|(<!DOCTYPE\s+\w+\s+\[[\s\S]*?\]>)|(<!\w[\s\S]*?>)/g, '')
                .replace(/(href\s*=\s*(?:"))/ig, 'href="/#')
                .replace(/(href\s*=\s*(?:'))/ig, "href='/#");



            this.response = restr;


        })
        .catch(error => this.status = error );

}

你怎么看,这个方法,把响应放在变量,并用正则表达式解析字符串
好​​的,然后我将它添加到div,就像这样

How you do you see, this method, put response in variable, and parse string by regular expressions Ok, and next I add it to div, like this

<div [innerHTML]="response | safe"></div>

好,我的页面显示。但是,脚本不起作用。它们存在于div标签中,但不会执行。

Good, my page is display. But, scripts doesn't work. They are exist in the div tag, but doesn't execute.

我曾尝试用 eval()但结果很差

let scripts: string[] = restr.match(/\<scr[\s\S]*?ipt>/g);

            this.srcfield.nativeElement.innerHTML = '';

            scripts.forEach((value, index) => {
                eval.call(null, (this.srcfield.nativeElement.innerHTML = value));
            });




SyntaxError:意外的令牌<

SyntaxError: Unexpected token <

为什么 innerHTML 不执行加载的脚本标记?我如何解决这个问题?

Why innerHTML doesn't execute loaded script tags? How i can fix that?

推荐答案

基于Adam的解决方案,您可以实现自定义指令以及管道并重新插入脚本到DOM中。这将解释两种情况:内联脚本和src脚本。请记住,允许这样的脚本是非常危险的。

Based on the Adam's solution you can implement a custom directive along with the pipe and re-insert scripts into the DOM. This would account for both cases: inline scripts and "src" scripts. Keep in mind that allowing scripts like so is very dangerous.

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) { }

    transform(html) {
        return this.sanitizer.bypassSecurityTrustHtml(html);
    }
}

指令:

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({ selector: '[runScripts]' })
export class RunScriptsDirective implements OnInit {
    constructor(private elementRef: ElementRef) { }
    ngOnInit(): void {
        setTimeout(() => { // wait for DOM rendering
            this.reinsertScripts();
        });
    }
    reinsertScripts(): void {
        const scripts = <HTMLScriptElement[]>this.elementRef.nativeElement.getElementsByTagName('script');
        const scriptsInitialLength = scripts.length;
        for (let i = 0; i < scriptsInitialLength; i++) {
            const script = scripts[i];
            const scriptCopy = <HTMLScriptElement>document.createElement('script');
            scriptCopy.type = script.type ? script.type : 'text/javascript';
            if (script.innerHTML) {
                scriptCopy.innerHTML = script.innerHTML;
            } else if (script.src) {
                scriptCopy.src = script.src;
            }
            scriptCopy.async = false;
            script.parentNode.replaceChild(scriptCopy, script);
        }
    }
}

用法:

<div [innerHTML]="myDynamicMarkup | safeHtml" runScripts></div>

这篇关于Angular 2如何从innerHTML执行脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆