Listen to events inside iFrame

So, I have a main page (a) and a preview page (b) embedded in the main page via an iframe. Page (b) raises a special event:

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

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

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

However, the above code does not work. Any ideas?

+4
source share
2 answers

jQuery trigger()only calls callbacks that were added through .on()its own instance. That way, the jQuery in your iframe will only initiate callbacks that were set using this instance, and not any settings through the jQuery instance of your main page.

dispatchEvent()

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

window.onMessage/window.postMessage Broadcast Channel api

window.onMessage/window.postMessage,

//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");

API onMessage/postMessage,

//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');
+2

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

0

Source: https://habr.com/ru/post/1688612/


All Articles