如何删除iFrame添加的beforeunload事件监听器?
问题描述:
如何删除iFrame添加的beforeunload事件侦听器? 我的情况是我负载添加一些beforeunload事件到DOM的iframe,我想在会话过期(或说某个特定事件)时删除它,并且我不想向用户显示确认消息。那么有没有什么办法可以从iframe中使用javascript删除事件侦听器?任何帮助将不胜感激。如何删除iFrame添加的beforeunload事件监听器?
// parent.html
<!DOCTYPE html>
<html>
<head>
<title>Parent Frame</title>
<script>
window.addEventListener('beforeunload', function(event) {
console.log('I am the 1st one.');
});
window.addEventListener('unload', function(event) {
console.log('I am the 3rd one.');
});
</script>
</head>
<body>
<iframe src="child-frame.html"></iframe>
</body>
</html>
// child.html
<!DOCTYPE html>
<html>
<head>
<title>Child Frame</title>
<script>
window.addEventListener('beforeunload', function(event) {
console.log('I am the 2nd one.');
});
window.addEventListener('unload', function(event) {
console.log('I am the 4th and last one…');
});
</script>
</head>
<body>
☻
</body>
</html>
答
我只能在chrome上重现此行为,FF似乎并没有通过iframe激发事件。
一个解决办法,我发现(可能不是最好的),是离开页面之前删除的iframe:
mainWindow.onbeforeunload = e => { iframe.parentNode.removeChild(iframe) };
这样一来,该事件不会冒泡的iframe的窗口了。
// toggle the blocking script
inp.onchange =
e => window.onbeforeunload = inp.checked ?
blockMessage :
null;
function blockMessage(e){
iframe.parentNode.removeChild(iframe);
}
<h3>click "Run code snippet" again</h3>
<label>block iframe's beforeunload<input type="checkbox" id="inp"></label><br>
<iframe id="iframe" src="data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%3Eonbeforeunload%20%3D%20e%20%3D%3E%20%22bye%22%3B%3C%2Fscript%3E%3C%2Fhead%3E%3C%2Fhtml%3E"></iframe>
<!-- Decoded iframe content :
<html>
<head>
<script>
\t onbeforeunload = e => "bye";
</script>
</head>
</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);
你需要改变事件侦听器的'child.html'添加的方式 - 我猜你可以改变'child.html'代码,对不对? –