如何删除 iFrame 添加的 beforeunload 事件监听器? 我的情况是我加载的 iframe 添加了一些 beforeunload 事件到 DOM,我想删除这些事件,以防 session 过期(或者说对于特定事件)并且我不想向用户显示确认消息。那么有什么方法可以使用 javascript 从 iframe 中删除事件监听器吗?任何帮助将不胜感激。
// 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>
最佳答案
单独编写添加事件监听函数。以便可以使用它来删除监听器。
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);
关于javascript - 如何删除 iFrame 添加的 beforeunload 事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272776/