繁体   English   中英

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

[英]Kill execution of a running script tag in Angular 11

目前我有一个 Angular 组件,它使用 Renderer2 库将脚本标签列表附加到 DOM 中,这些脚本的代码是从外部源检索的。 在以下代码段中, 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)
}

好的,我被告知了一种方法,它可以完美地工作。

Instead of creating scripts, I can create an iframe and pass all the scripts using the attribute srcdoc from the iframe, this would be the structure I want to create from the Angular component and append to the DOM, I should be creating an iframe per script :

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

因此,要创建和 append 来自 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])
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM