【问题标题】:how to call a function from iframe如何从 iframe 调用函数
【发布时间】:2019-08-09 14:47:42
【问题描述】:

我在 iframe 中放置了一个 Angular 应用,我想调用他的函数。

<iframe #iframe frameborder="0" src="http://localhost:4200/edit/username"></iframe>

http://localhost:4200/edit/username这个链接是page-editor的一个组件

export class PageEditorComponent implements OnInit...{
 @Input() eventMessage = { message: ''};

 handleEvent(eventMessage: { message: string; page: string }) {
    // if there are any possibility to put somethings in eventMessage 
    if (eventMessage.message.includes('tablette')) {
      this.loadIframe('tablette');
    }

  }
}

我的目标是从 iframe 调用 PageEditorComponent 的任何函数

【问题讨论】:

  • 您的组件是否已加载到 iframe 中?
  • 是的,一切正常
  • 在这种情况下,ngOnInit 方法应该在组件加载时被触发。那不是被解雇了吗?
  • 是的,但是我在 iframe 下有一个保存按钮,我的目的是当我点击这个按钮时我想保存数据,并且功能保存在 iframe 内
  • 是的。所以你试图从 iframe 内部到外部进行交互。在这种情况下,窗口对象具有可用于实现此事件的方法。当你点击保存时,你使用 window.postMessage 发布一个事件。并且您的代码的另一端将不得不对此保持警惕。然后调用实际的保存方法。希望没有混乱?

标签: javascript angular iframe


【解决方案1】:

查看此问题的另一种方法是使用 Window.postMessage() API 从 iframe 内部与外部进行通信。你的角度代码将不得不寻找消息/事件。它更像是一个消息总线,用于双方之间的通信。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多