2017-07-24 105 views
1

如何刪除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> 
+0

你需要改變事件偵聽器的'child.html'添加的方式 - 我猜你可以改變'child.html'代碼,對不對? –

回答

1

我只能在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> 
 
-->

0

寫單獨添加事件監聽器函數。以便它可以用來刪除監聽器。

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); 
+0

我必須從主機中移除iframe的事件 – Abhijeet

+0

您指的是主機? –

+0

父html是這裏的主機 – Abhijeet