簡體   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