Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: listen for postMessage events from specific iframe

I have multiple iframes in a page. Now I have one message event listener for the page, which gets the messages from all of the iframes. I have a workaround to know from which iframe the message is coming.

I would like to make event listeners for each iframe separately. Is this possible?

like image 725
forresto Avatar asked Apr 28 '13 18:04

forresto


3 Answers

You must listen on the global message event of the window object, but you can filter the source iframe using the source property of MessageEvent.

Example:

const childWindow = document.getElementById('test-frame').contentWindow; window.addEventListener('message', message => {     if (message.source !== childWindow) {         return; // Skip message in this event listener     }      // ... }); 
like image 189
Congelli501 Avatar answered Sep 25 '22 21:09

Congelli501


If the src attribute of each iframe is unique then you can try this:

On the child:

function sendHeight() {   // sends height to parent iframe   var height = $('#app').height();   window.parent.postMessage({     'height': height,     'location': window.location.href   }, "*"); }  $(window).on('resize', function() {   sendHeight(); }).resize(); 

On the parent:

$(window).on("message", function(e) {     var data = e.originalEvent.data;     $('iframe[src^="' + data.location + '"]').css('height', data.height + 'px'); }); 

The child sends it's height and URL to the iframe parent using postMessage(). The parent then listens for that event, grabs the iframe with that URL and sets the height to it.

like image 39
Jan Werkhoven Avatar answered Sep 24 '22 21:09

Jan Werkhoven


Actually you can. Add a unique name attribute to each iframe. iframe name is passed down to the contentWindow. So inside iframe window.name is the name of the iframe and you can easily send it in post message.

like image 33
Maciej Krawczyk Avatar answered Sep 25 '22 21:09

Maciej Krawczyk