Invoke Ember action from plain JavaScript in iframe

那年仲夏 提交于 2019-12-24 02:09:20

问题


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

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?


回答1:


You will face 2 problems.

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

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)

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)



来源:https://stackoverflow.com/questions/39748837/invoke-ember-action-from-plain-javascript-in-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!