6
votes

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.

1
receiveMessage is using the variable origin that has never been set. So it returns. - Barmar
You also have console.log(event) outside the function with the event parameter. What's that supposed to do? - Barmar
I guess origin should be event.origin, but why are you even bothering with that? It can never be *, it's always a URL. - Barmar
@Barmar I'm pretty shaky outside of jQuery and I have been trying different combos of syntax for about an hour or two. I even had removed the if statement with the idea that receiving the message would just fire the console log - but no luck. Then I thought that maybe origin was required so put it back in. I can't seem to get anything to "happen" in the recieveMessage function, what should I put? The console.log(event) was just to see if anything showed up. Saw someone else do it on a SE question and thought I'd try it. - Daniel
You're sending the message before the page in the iframe has loaded and added the message event listener. I used setTimeout to delay the sending code by 1 second and it worked. - Barmar

1 Answers

7
votes

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", "*");
});