且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular2动态插入脚本标签

更新时间:2023-11-26 16:19:34

这不是一个角度2的问题, script 通过innerHTML插入的标签不会被执行。



如果您的html字符串包含脚本标签,则可以这样插入:

  const fragment = document.createRange()。createContextualFragment(yourHtmlString); 
anyElement.appendChild(fragment);


I'm getting from server content into json object field, where it is html, <style></style> and <script></script> tags, and I want to execute it like this:

[innerHtml]="content | sanitize", but <script></script> tags do not execute. Is it possible to make it work?

My sanitize pipe looks like this:

import {Pipe} from '@angular/core';
import {DomSanitizationService} from '@angular/platform-browser';

@Pipe({
    name: 'sanitize',
    pure: true
})
export class Sanitize {
    constructor(private sanitizer: DomSanitizationService) {

    }

    transform(html: string) {

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

I know, that there is bypassSecurityTrustScript function in DomSanitizationService, but how can I use it in my case?

It's not an angular 2's problem, script tags inserted via innerHTML are not executed.

If you have html string that contains script tags insert it this way:

const fragment = document.createRange().createContextualFragment(yourHtmlString);
anyElement.appendChild(fragment);