Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何删除iFrame添加的beforeunload事件侦听器?_Javascript_Iframe_Browser_Addeventlistener_Onbeforeunload - Fatal编程技术网

Javascript 如何删除iFrame添加的beforeunload事件侦听器?

Javascript 如何删除iFrame添加的beforeunload事件侦听器?,javascript,iframe,browser,addeventlistener,onbeforeunload,Javascript,Iframe,Browser,Addeventlistener,Onbeforeunload,如何在卸载iFrame添加的事件侦听器之前删除它们? 我的例子是我加载的iframe,将一些beforeunload事件添加到DOM中,我希望在会话过期(或者说对于某个特定事件)并且我不想向用户显示确认消息时删除这些事件。那么,是否有任何方法可以使用javascript从iframe中删除事件侦听器?任何帮助都将不胜感激 //parent.html 父帧 window.addEventListener('beforeunload',函数(事件){ console.log('我是第一个'); }

如何在卸载iFrame添加的事件侦听器之前删除它们? 我的例子是我加载的iframe,将一些beforeunload事件添加到DOM中,我希望在会话过期(或者说对于某个特定事件)并且我不想向用户显示确认消息时删除这些事件。那么,是否有任何方法可以使用javascript从iframe中删除事件侦听器?任何帮助都将不胜感激

//parent.html


父帧
window.addEventListener('beforeunload',函数(事件){
console.log('我是第一个');
});
window.addEventListener('unload',函数(事件){
console.log('我是第三个');
});
//child.html


子框架
window.addEventListener('beforeunload',函数(事件){
console.log('我是第二个');
});
window.addEventListener('unload',函数(事件){
log('我是第四个也是最后一个…');
});
☻

单独编写添加事件侦听器函数。以便可以使用它删除侦听器

function beforeUnload(event) {
   console.log('I am the 2nd one.');
};
// creating event listeners
window.addEventListener('beforeunload', beforeUnload);

// remove when you don't want the listener
window.removeEventListener('beforeunload', beforeUnload);

我只能在chrome上重现这种行为,FF似乎不会在iFrame上触发事件

我发现的一个解决方法(可能不是最好的)是在离开页面之前删除iframe:

mainWindow.onbeforeunload = e => { iframe.parentNode.removeChild(iframe) };
这样,事件就不再冒泡到iframe的窗口

//切换阻止脚本
inp.onchange=
e=>window.onbeforeunload=inp.checked?
区块消息:
无效的
功能块消息(e){
iframe.parentNode.removeChild(iframe);
}
再次单击“运行代码片段”
在卸载之前阻止iframe

您需要更改在
child.html
上添加事件侦听器的方式-我想您可以更改
child.html
上的代码,对吗?我必须将iframe的事件从主机删除到您所指的主机?父html是此处的主机
function beforeUnload(event) {
   console.log('I am the 2nd one.');
};
// creating event listeners
window.addEventListener('beforeunload', beforeUnload);

// remove when you don't want the listener
window.removeEventListener('beforeunload', beforeUnload);
mainWindow.onbeforeunload = e => { iframe.parentNode.removeChild(iframe) };