【发布时间】:2026-01-02 07:25:01
【问题描述】:
如何删除 iFrame 添加的 beforeunload 事件侦听器? 我的情况是我加载的 iframe 向 DOM 添加了一些 beforeunload 事件,我想在会话过期(或者说针对特定事件)的情况下将其删除,并且我不想向用户显示确认消息。那么有什么方法可以使用 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>
【问题讨论】:
-
您需要更改在
child.html上添加事件侦听器的方式 - 我想您可以更改child.html上的代码,对吧?
标签: javascript iframe browser addeventlistener onbeforeunload