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?

up vote 5 down vote accepted

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)

  • Thanks. Actually I also came up with this solution and used the window.parent.postMessage to create an event that ember listens to. Ember actions seem to be really isolated from the outside javascript environment. – Bijan Sep 29 '16 at 10:03

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.