从iframe中的纯JavaScript调用Ember操作 [英] Invoke Ember action from plain JavaScript in iframe

查看:172
本文介绍了从iframe中的纯JavaScript调用Ember操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌入在ember应用程序中的iframe我如何从iframe中调用组件的方法?

I have an iframe embedded in an ember app. How can I call a component's method from within the iframe?

我想我需要通过window.parent获取ember实例,但是如何做到这一点,特别是如何触发垃圾动作?

I guess I somehow need to get the ember instance via window.parent but how to do it and especially how to trigger an ember action?

推荐答案

您将遇到2个问题。

首先,直到框架的内容从与应用程序相同的域加载,它是完全孤立的。但是有一种方法可以与这种框架进行通信, window.postMessage

First, until frame's content is loaded from the same domain as app, it's completely isolated. But there is a way to communicate with such frame, window.postMessage

所以,在iframe中,应该执行这样的代码:

So, within iframe, such code should be executed:

window.parent.postMessage({action: 'sayHi'}, '*');

第一个参数是要发送到父窗口的数据(我在那里放置动作字段,但可以添加您需要通过的其他信息)

First argument is data to send to parent window (i put just action field there, but you can add other info that you need to pass)

第二个问题是调用余烬操作。我建议在应用程序路由的 beforeModel 钩子之间定义消息侦听器。当用户加载应用程序时,这个钩子将被执行一次。

Second problem is calling an ember action. I'd suggest to define message listener inside application route's beforeModel hook. This hook will be executed once, when user loads app. That makes it a right place.

beforeModel() {
  window.addEventListener("message", receiveMessage, false);

  var that = this;
  function receiveMessage(event) {
    var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
    // Here you want to check origin, but in twiddle its null, try on ur machine...
    var data = event.data;
    if (data.action !== undefined) {
      that.send(data.action);
    }
  }
}

此代码将调用应用程序路由的动作。在他们里面你会操纵你的应用程序。我创建了一个演示此方法的旋转

This code will call application route's actions. Inside them you will manipulate your app. I created a twiddle that demonstrates this approach.

(抱歉,格式不好,代码不太干净,只是稍晚)

(Sorry about poorly formatted and not very clean code, it's just a bit late)

这篇关于从iframe中的纯JavaScript调用Ember操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆