Skip to content Skip to sidebar Skip to footer

Invoke Ember Action From Plain Javascript In Iframe

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

Solution 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;
  functionreceiveMessage(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)

Post a Comment for "Invoke Ember Action From Plain Javascript In Iframe"