Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  165] [ 5]  / answers: 1 / hits: 23953  / 7 Years ago, thu, november 2, 2017, 12:00:00

So I have a main page (a) and a preview page (b) embedded into the main page via an iframe. The page (b) triggers a special event:



$(document).trigger('preview.compiled');


Now I want the main page (a) to listen to this event and do something then:



$('iframe').contents().on('preview.compiled', function() {
console.log('Success');
});


However, the code above doesn't work. Any ideas?


More From » jquery

 Answers
9

jQuery's trigger() only triggers the callbacks that were added through .on() of its own instance. So the jQuery within your iframe is only going to trigger the callbacks that were set using that instance, not any set through the jQuery instance of your main page.



You could instead call dispatchEvent() passing in your own event object



document.dispatchEvent(new Event('preview.compiled'));


Or can instead use window.onMessage / window.postMessage or Broadcast Channel api with modern browsers



window.onMessage / window.postMessage, check browser support



//in main window
window.addEventListener('message',function(message){
if(message.data.type==preview.compiled){
//do something
}
});

//in iframe
parent.postMessage({
type:preview.compiled,
other:other data to pass
},url of main window);


Broadcast Channel API onMessage/postMessage, check browser support



//Main window
var bc = new BroadcastChannel('preview:compiled');
bc.onmessage = function(message){
console.log(message.data);
};

//iframe
var bc = new BroadcastChannel('preview:compiled');
bc.postMessage('Some data');

[#56029] Tuesday, October 31, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;