javascript - Angular:在 iFrame 中运行脚本

标签 javascript html angular iframe

我将 HTML 作为字符串作为 API 响应。 HTML 包含一些内部脚本标签,这些标签具有在 $(window).load() 下调用的函数。如何在我的 Angular 应用程序中加载此 HTML。

我尝试将 HTML 字符串响应附加到 iFrame 正文。 HTML 会加载,但脚本标记不会执行,因为 Angular 路线更改时不会触发 window.load 事件。

我该如何解决这个问题。 这是我的代码:

组件.ts

ngOnInit() {
   const html = "
       <html>
         <body>
             <h1>Hello world</h1>
             <script>
               $(window).on('load', function() {
                 console.log('I am in the function') 
               })
             </script>
         </body>
      </html>"
   this.iframeDoc = this.iframe.nativeElement.contentDocument
   this.iframeDoc.body.innerHTML = html;
}

组件.html

<iframe #iframe></iframe>

我希望在附加 iframe 内容时记录“我在函数中”。

编辑:

我还尝试将 HTML 附加到 div 而不是 iFrame。代码如下:

组件.html

<div id="wrapper" appRunScripts></div>

组件.ts

ngOnInit() {
   const html = "
       <html>
         <body>
             <h1>Hello world</h1>
             <script>
               $(window).on('load', function() {
                 console.log('I am in the function') 
               })
             </script>
         </body>
      </html>"
   const wrapper = document.getElementById('wrapper');
   wrapper.innerHTML = html;
}

还添加了在 HTML 中运行脚本的指令。这是指令 运行脚本.directive.ts

import { Directive, ElementRef, OnInit  } from '@angular/core';

@Directive({
  selector: '[appRunScripts]' 
})
export class RunScriptsDirective implements OnInit {

  constructor(private elementRef: ElementRef) { }
  ngOnInit(): void {
      setTimeout(() => { // wait for DOM rendering
          this.reinsertScripts();
      });
  }
  reinsertScripts(): void {
      const scripts = <HTMLScriptElement[]>this.elementRef.nativeElement.getElementsByTagName('script');
      const scriptsInitialLength = scripts.length;
      for (let i = 0; i < scriptsInitialLength; i++) {
          const script = scripts[i];
          const scriptCopy = <HTMLScriptElement>document.createElement('script');
          scriptCopy.type = script.type ? script.type : 'text/javascript';
          if (script.innerHTML) {
              scriptCopy.innerHTML = script.innerHTML;
          } else if (script.src) {
              scriptCopy.src = script.src;
          }
          scriptCopy.async = false;
          script.parentNode.replaceChild(scriptCopy, script);
      }
  }

}

最佳答案

ngAfterViewInit() {
    let content = `<html>
         <body>
             <h1>Hello world</h1>
             <script>
               $(window).on('load', function() {
                 console.log('I am in the function') 
               })
             </script>
         </body>
      </html>`;
    let doc = this.iframeDoc.nativeElement.contentDocument || this.iframeDoc.nativeElement.contentWindow;
    doc.open();
    doc.write(content);
    doc.close();
  }

在右侧 lyfecycle Hook 中访问您的 iframe

ngAfterViewInit - 在组件 View 完全初始化后调用的生命周期 Hook

如果你想运行脚本。注入(inject):

 constructor(private sanitizer: DomSanitizer) {
    this.script = this.sanitizer.bypassSecurityTrustHtml(this.script);
  }

ngAfterViewInit() {
 let scripts = this.div.nativeElement.getElementsByTagName('script');
  for (let script of scripts) {
    eval(script.text)
  }
}

模板:

<div #content [innerHTML]="script"> </div>

CODE EXAMPLE

关于javascript - Angular:在 iFrame 中运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573829/

相关文章:

angular - 火力警告 : Cannot read property 'myID' of undefined

javascript - Angular 2 - 全局错误处理程序仅在未捕获错误时执行

javascript - 使用 PHP 或 JS 对 @media 查询中的 html 元素进行优先级排序

如果数字没有连字符,则javascript正则表达式删除引号

php - 如何禁用 symfony 2.3 中特定按钮的 html5 验证

php - Wordpress嵌入式视频问题

Angular 2 服务错误。找不到原因

javascript - map 究竟如何排序键?

javascript - MongoDB 创建用于测试的数据库

php - 通过 PHP header 或 HTML 元 http-equiv 发送文档信息?