执行可信脚本
Execute trusted script
这是一个组件的简约示例
export class AppComponent {
htmlSnippet: string;
constructor(private sanitizer: DomSanitizer) {
this.htmlSnippet = this.sanitizer.sanitize(
SecurityContext.HTML,
`<p>snippet works!</p><script>alert("ddd");</script>`
);
}
}
和模板
<p>app works!</p>
<div [innerHTML]="htmlSnippet"></div>
所有内容都已呈现。 CSS 如果有的话也可以。
有没有办法执行该警报?
您可以只创建脚本标签并将其附加到组件的正文中
constructor(private renderer2: Renderer2, private el: ElementRef) {}
ngAfterViewInit() {
let scriptEl = document.createElement("script");
scriptEl.innerText = "alert('hello')";
this.renderer2.appendChild(this.el.nativeElement, scriptEl);
}
according to this issue you can't put a script tag in the body of
the template because it going to be removed the only way around this
is to insert the script tag dynamically as above.
这是一个组件的简约示例
export class AppComponent {
htmlSnippet: string;
constructor(private sanitizer: DomSanitizer) {
this.htmlSnippet = this.sanitizer.sanitize(
SecurityContext.HTML,
`<p>snippet works!</p><script>alert("ddd");</script>`
);
}
}
和模板
<p>app works!</p>
<div [innerHTML]="htmlSnippet"></div>
所有内容都已呈现。 CSS 如果有的话也可以。
有没有办法执行该警报?
您可以只创建脚本标签并将其附加到组件的正文中
constructor(private renderer2: Renderer2, private el: ElementRef) {}
ngAfterViewInit() {
let scriptEl = document.createElement("script");
scriptEl.innerText = "alert('hello')";
this.renderer2.appendChild(this.el.nativeElement, scriptEl);
}
according to this issue you can't put a script tag in the body of the template because it going to be removed the only way around this is to insert the script tag dynamically as above.