收听iFrame中的事件 [英] Listen to events inside iFrame
问题描述
因此,我有一个主页(a)和一个预览页(b)通过iframe嵌入到主页中.页面(b)触发一个特殊事件:
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');
现在,我希望主页(a)收听此事件,然后执行以下操作:
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?
推荐答案
jQuery的trigger()
仅触发通过其实例的.on()
添加的回调.因此,iframe中的jQuery只会触发使用该实例设置的回调,而不会触发通过主页jQuery实例设置的任何回调.
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.
您可以改为调用dispatchEvent()
并传入您自己的事件对象
You could instead call dispatchEvent()
passing in your own event object
document.dispatchEvent(new Event('preview.compiled'));
或者可以改用 window.onMessage/window.postMessage 或使用现代浏览器的广播频道api
window.onMessage/window.postMessage,检查浏览器支持
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");
广播频道API onMessage/postMessage,检查浏览器支持
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');
这篇关于收听iFrame中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!