Google chrome onbeforeunload wrong behavior with iframe

安稳与你 提交于 2019-12-04 17:16:40

问题


Let say I have two pages. One of them contains another one inside as iframe. If you subscribe to onbeforeunload event on the parent page, then this event doesn't triggers if you close tab when iframe is in focus. I suppose it is a bug as written here: Google Chrome issues

But I mentioned that, for example, google docs handle this situation. Can anyone give me a solution? Important note that I have no actual access to the iframe content as it is a third party html editor (WYSIWYG).


回答1:


I know it is an old question but just to help people who are coming here through Search :

The bug is fixed by now here.

Since chrome 10, the issue should be fixed.

There is a related bug though here.

So, in short if you still not able to fire "onbeforeunload" on frames, it could be due to change in the content through JavaScript like document.open document.write document.close etc.




回答2:


the below code will work across all the browsers

if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('beforeunload', test, false);
}
else if (typeof document.addEventListener != 'undefined') {
    document.addEventListener('beforeunload', test, false);
}
else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onbeforeunload', test);
}

else {
    if (typeof window.onbeforeunload == 'function') {
        window.onbeforeunload = function() {
            test();
        };
    }
    else {
        window.onbeforeunload = test;
    }
}

function test(){ alert('working');}

try this once ...




回答3:


You may also try to change the iframe's url to "about:blank", e.g.:

$("#myFrameId")[0].src = "about:blank";

It forces chrome to "cleanly" close the window containted within the iframe.

Just to mention: if you want to close only your iframe but not the parent window, you have to give chrome enough time to execute the handler you've attached to 'onbeforeunload'.



来源:https://stackoverflow.com/questions/1601388/google-chrome-onbeforeunload-wrong-behavior-with-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!