gpt4 book ai didi

angular - 执行可信脚本

转载 作者:行者123 更新时间:2023-12-03 21:42:45 25 4
gpt4 key购买 nike

这是一个简单的组件示例

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 也能正常工作。

enter image description here

有没有办法执行该警报?

最佳答案

您可以只创建脚本标签并将其附加到组件主体

  constructor(private renderer2: Renderer2, private el: ElementRef) {}

ngAfterViewInit() {
let scriptEl = document.createElement("script");
scriptEl.innerText = "alert('hello')";

this.renderer2.appendChild(this.el.nativeElement, scriptEl);
}

demo 🚀

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.

关于angular - 执行可信脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59358371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com