bypassSecurityTrustScript
不应该运行任何东西。它唯一要做的就是将提供的值包装到SafeScript中,以便在模板绑定中使用它时绕过清理。它不对值执行任何转换。
官方文档展示了如何使用样式、URL 和 HTML 的相似值。这就是事情变得有点奇怪的地方。
似乎可以像这样在模板中使用 SafeScript 值:
<script [innerHtml]="safeScript"></script>
但实际上它不起作用,因为 Angular 会清除模板中的所有<script>
标签。
请记住,从字符串运行 JS 存在安全风险,因此在执行之前应该三思而后行。如果没有其他方法可以执行此操作,则可以使用更“传统”的 JS 方法来执行此操作,包括eval
Function constructor。
也可以<script>
直接将 a 添加到 DOM(通过使用全局document
对象或Rendered)
import { Component, Renderer2, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
//...
export class ButtonOverviewExample {
constructor(
private renderer: Renderer2,
@Inject(DOCUMENT) private document: HTMLDocument
) {}
test() {
const script = this.renderer.createElement("script");
this.renderer.setProperty(
script,
"text",
"console.log('Hello World')"
);
// It will add a new `<script>` on each call
this.renderer.appendChild(this.document.body, script);
}
}