如何从 Ionic 4 中的 TypeScript 文件调用 iframe 显示的网页中的 JavaScript 函数?

How do I call a JavaScript function in the webpage displayed by an iframe, from a TypeScript file in Ionic 4?

如何从我的 .page.ts 文件中调用带有参数 (foo('bar','yadda')) 的 JavaScript 函数?

我有一个带有 <iframe> 的页面的 Ionic 4 应用程序,我需要在 <iframe> 显示的页面中调用 JavaScript。 .html 文件如下所示:

<ion-header>
</ion-header>

<ion-content>
  <iframe class='webPage' name="samplePage" [src]="cleanURL" width="100%" height="100%">
  </iframe>
</ion-content>

我在我的 .page.ts 文件中初始化 <iframe>,如下所示:

ionViewDidEnter() {
  this.url = "https://example.com/mylegacysite"+ '?' + this.someParameter;
  this.cleanURL = this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}

初始化正常。但是稍后,能够 运行 https://example.com/mylegacysite 上的 JavaScript 函数而不是更新 this.cleanURL

会更有效率

不同的域,无法调用方法或直接访问 iframe 的内容文档。

您需要使用cross-document messaging

例如在顶部window:

myIframe.contentWindow.postMessage('Hello', '*');

在您的 iframe 中:

window.onmessage = function(e){
if (e.data == 'Hello') {
    alert('It works!');
}

};