Daniel
Daniel

Reputation: 792

Using postMessage() isn't being received

I'm sure it's just a problem with my syntax but I am trying to send a variable to an iframe (for colorbox to use). For the time being I am accepting any domains on both ends (just to get it to work). Here is the js for the sending page:

$(document).ready(function() {
 if(window.location.hash) {
  var urlimage = window.location.hash.substring(1);
  targetiframe = document.getElementById('wbgallery').contentWindow;
  targetiframe.postMessage(urlimage, "*");
  console.log(urlimage);
 }
});

And here is the receiving page:

$(document).ready(function() {    
 window.addEventListener('message',receiveMessage);
 console.log(event);
 function receiveMessage(event) {
   if (origin !== "*")
   return;
   inbound = event.data;
   console.log(inbound);
 }
});

I see the console log for urlimage and can see an event but nothing for inbound. I'm using Mozilla's explanation to try and work it all out.

Upvotes: 8

Views: 18451

Answers (1)

Barmar
Barmar

Reputation: 781255

You're sending the message before the page in the iframe has loaded, so the message listener hasn't been established yet.

You can have the iframe send a message to the parent when it's ready, and then send the message after this.

Parent code:

$(document).ready(function() {
  if (window.location.hash) {
    var urlimage = window.location.hash.substring(1);
    var targetiframe = document.getElementById('wbgallery').contentWindow;
    $(window).on("message", function(e) {
      targetiframe.postMessage(urlimage, "*");
      console.log(urlimage);
    });
  }
});

Iframe code:

$(document).ready(function() {
  $(window).on('message', function(event) {
    inbound = event.data;
    console.log(inbound);
  });
  window.parent.postMessage("ready", "*");
});

Upvotes: 16

Related Questions