4

我有一个字符串格式的受信任的 Javascript/Angular 脚本,我想在 Angular 组件中执行它。我知道这就是 Domsanitizer bypassSecurityTrustScript() 的作用。Angular Domsanitizer

但是,当尝试在我的组件中运行时,什么也没有发生。我如何使用它从字符串运行 js 代码?这就是我到目前为止所做的,在下面以及在 stackblitz Custom Script StackBlitz中提前致谢。

我的组件.ts

constructor(private domSanitizer: DomSanitizer)
test(){
 let code: string = "console.log('Hello World')";
 this.domSanitzer.bypassSecurityTrustScript(code);
}
4

1 回答 1

4

bypassSecurityTrustScript不应该运行任何东西。它唯一要做的就是将提供的值包装到SafeScript中,以便在模板绑定中使用它时绕过清理。它不对值执行任何转换。 官方文档展示了如何使用样式、URL 和 HTML 的相似值。这就是事情变得有点奇怪的地方。

似乎可以像这样在模板中使用 SafeScript 值:

<script [innerHtml]="safeScript"></script>

但实际上它不起作用,因为 Angular 会清除模板中的所有<script>标签。

请记住,从字符串运行 JS 存在安全风险,因此在执行之前应该三思而后行。如果没有其他方法可以执行此操作,则可以使用更“传统”的 JS 方法来执行此操作,包括evalFunction 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);
  }
}
于 2020-04-19T17:24:54.267 回答