Search code examples
javascriptiframeembed

Communication between child iframes


I have built a player which is embedded via an iframe. If two players are embedded, I want to stop one if the other starts to play. So the question is, is it possible to use postMessage to communicate between two children iframes, without owning the parent? Vimeo is doing this somehow. If I embed two vimeo players, and play one, then the other, the second player stops the first. How? (proof: https://jsfiddle.net/3fy14orw/2/)

Within my player, I am using postMessage to fire off an event on the parent window when my player plays. I've confirmed this is working. I've tried using my actual origin as well as "*" for the origin.

//in my player
window.parent.postMessage(data, "*");

How can the other player know? I've tried,

//tried adding this in my player    
window.parent.addEventListener('message', function(evt) {});

But this throws an error.

"SecurityError: Blocked a frame with origin..."

I've also tried naming my frame windows, as well as accessing these via the window.parent.frames object, but this also throws a CORS issue.

Assumptions:

  • My players share the same origin.
  • My player can be embedded on any domain, not just my own

Solution

  • Kinda hacky, but you could build a communication channel on top of localStorage. Frames could send messages by writing to localStorage, and then read messages by constantly polling localStorage for changes.