在 Angular 11 中终止执行 运行 脚本标签

Kill execution of a running script tag in Angular 11

目前我有一个 Angular 组件将脚本标签列表附加到 DOM with Renderer2 库中,这些脚本的代码是从外部源检索的。在以下代码段中,scripts 数组是源链接列表。在这种情况下,我无法修改他们的 JS 代码:

  for(let i = 0; i<scripts.length; i++){
    let script = this.renderer2.createElement('script');
    script.type = `text/javascript`;
    script.src = scripts[i];
    this.appendedChildren.push(script);
    this.renderer2.appendChild(this._document.body, script);
}

我试图从 DOM 中删除它们,但脚本继续执行:

ngOnDestroy(){
  for(let i = 0; i<this.appendedChildren.length; i++)
    this.renderer2.removeChild(this._document.body, this.appendedChildren[i]);
}

我想要的是让 pid 或某种标识符能够终止 ngOnDestroy() 中的 JS 脚本,以及这样做的方法。

constructor(private renderer: Renderer2) {}

let script = this.renderer.createElement('script');
script.type = `text/javascript`;
script.src = 'testme.js';
script.id = "testScriptName";
this.renderer.appendChild(this._document.body, script);

ngOnDestroy() {
var elem = document.querySelector("#testScriptName");
document.querySelector("#testScriptName").parentNode.removeChild(elem)
}

好的,有人告诉我一种方法,而且效果很好。

我可以创建一个 iframe 并使用来自 iframe 的 srcdoc 属性传递所有脚本,而不是创建脚本,这将是我想从 Angular 组件并附加到 DOM,我应该为每个脚本创建一个 iframe:

  <iframe class="iframe-container" srcdoc='
  <html>
    <head></head>
    <body>
      <script src="https://script-source.com"></script>
    </body>
  </html>'>
</iframe>

因此,要从 Angular 组件创建和附加脚本,请注意我正在将组件添加到附加的子数组中(我知道有更简洁的方法来执行此操作,只是为了获得想法):

let iframe = this.renderer2.createElement('iframe');
iframe.setAttribute('class', 'iframe-ad');
iframe.setAttribute('srcdoc', `
  <html>
    <head></head>
    <body>
      <script src="https://src-example-url.com"></script>
    </body>
  </html>
`);

this.appendedChildren.push(iframe);
this.renderer2.appendChild(this._document.body.querySelector('div.iframe-holder'), iframe);

为了删除 iframe,只需将这些行添加到 ngOnDestroy() 即可:

ngOnDestroy(){
  for(let i = 0; i<this.appendedChildren.length; i++){
    this.renderer2.removeChild(this._document.body, this.appendedChildren[i])
  }
}