Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...