【问题标题】:Calling components function from iframe从 iframe 调用组件函数
【发布时间】:2017-01-12 14:50:48
【问题描述】:

我的窗口中有一个 iframe,我用 jquery 向它添加了新按钮。在迁移到 angular2 之前,我使用 parent.SampleFunction() 从 iframe 调用父函数。现在 parent 是一个角度组件,它不起作用。

export class AppComponent {

 // use jquery to find the iframe and put a button into it
 addButtonToIFrame() {
     ...
     let buttonHtml = "<button onClick='parent.SampleFunction()'></button>"
     ...
 }

 SampleFunction() {
  ...
 } 

}

我应该如何更改 onclick 功能以访问父级?

【问题讨论】:

    标签: angular iframe


    【解决方案1】:

    同源 iframe

    您可以安全地访问 window.parent 对象,因此您只需将您的 SampleFunction 放入全局 window 对象中。

    export class AppComponent {
    
     constructor(){
      (<any>window).SampleFunction= this.SampleFunction.bind(this);
     }
    
     // use jquery to find the iframe and put a button into it
     addButtonToIFrame() {
         ...
         let buttonHtml = "<button onClick='parent.SampleFunction()'></button>"
         ...
     }
    
     SampleFunction() {
      ...
     }
    } 
    

    如果您有多个相同类的实例并且您的 SampleFunction 处理组件状态,您可能需要为您的 SampleFunction 创建随机名称。

    您也可以使用PostMessage API,这应该是一个更灵活的选择。

    PostMessage API

    如果您正在处理来自另一个域的 iframe,您可以使用 PostMessage API:

    iframe 内的脚本

    window.parent.postMessage({foo:"foo"});
    

    父级内的组件

    export class AppComponent {
    
     @HostListener("window:message",["$event"])
     SampleFunction($event:MessageEvent) {
      if (event.origin !== "protocol://my-expected-domain.tdl:port")
        return;
      console.log($event.data)// {foo:"foo"}
     }
    
    } 
    

    当然,您必须对照 iframe 的实际域检查 event.origin

    【讨论】:

    • 您好,我正在使用您的上述方法,但我收到错误跨域脚本,您能否更新您的答案以允许跨域脚本我 shell 非常感谢您
    • 我为 postMessage API 添加了一个示例。
    • @n00dl3 这很有帮助。在我的情况下,子站点是一个 Angular 应用程序,但父站点不是。任何指针如何使用香草javascript在父级中创建一个监听器(如你的@HostListener)?对于上下文,我无法完全控制父页面。我可以提供自定义脚本(例如,我用来插入 iframe),所以我希望我也可以创建一个监听器。
    • @mike_butak 你可以在 mdn 上找到很多有用的信息:developer.mozilla.org/en-US/docs/Web/API/Window/… 你只需要在父页面上使用window.addEventListener("message",function(){})
    • @n00dl3 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多