Google chrome onbeforeunload wrong behavior with iframe

前端 未结 3 691
独厮守ぢ
独厮守ぢ 2021-02-13 20:18

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 yo

3条回答
  •  心在旅途
    2021-02-13 20:37

    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 ...

提交回复
热议问题