如何在Angular中使用Domsanizer bypassSecurityTrustScript()以字符串形式运行脚本

如何在Angular中使用Domsanizer bypassSecurityTrustScript()以字符串形式运行脚本,angular,angular-dom-sanitizer,Angular,Angular Dom Sanitizer,我有一个字符串格式的可信Javascript/Angular脚本,我希望在Angular组件中执行。我知道Domsanizer bypassSecurityTrustScript()就是这么做的 但是,当尝试在我的组件中运行时,什么都没有发生。如何使用它从字符串运行js代码?这是我到目前为止所做的,下面是我在stackblitz中所做的,提前感谢 mycomponent.ts constructor(private domSanitizer: DomSanitizer) test(){ let

我有一个字符串格式的可信Javascript/Angular脚本,我希望在Angular组件中执行。我知道Domsanizer bypassSecurityTrustScript()就是这么做的

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

mycomponent.ts

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

bypassSecurityTrustScript
不应运行任何内容。它所做的唯一一件事是将提供的值包装到中,以便在模板绑定中使用它时绕过清理。 它不会对值执行任何转换。 显示如何使用样式、URL和HTML的类似值。这就是事情变得有点奇怪的地方

似乎可以在模板中使用SafeScript值,如下所示:

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

谢谢,我在另一篇文章中看到了这个解决方案,似乎唯一的方法就是使用appendChild(希望不是这样,但你的解释现在有意义了)。因为我希望它仅限于一个组件,所以我希望使用eval代替某种形式的santizer,这样它就不会执行XSS潜在代码。
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);
  }
}