onbeforeunload support detection

前端 未结 10 1075
慢半拍i
慢半拍i 2020-11-28 11:21

I\'d like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work:

if (window.onbeforeu         


        
相关标签:
10条回答
  • 2020-11-28 11:49

    Different approach, get the typeof

    if(typeof window.onbeforeunload == 'function')
    
    {
    alert("hello functionality!");
    }
    
    0 讨论(0)
  • 2020-11-28 11:50

    Mobile browsers don't tend to not support beforeunload because the browser can go into the background without unloading the page, then be killed by the operating system at any time.

    However, all modern non-mobile browsers support it. Therefore, you can just check if the browser is a mobile browser.

    To solve the problem I use:

    var isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i);
    if (isMobile)
    {
        window.addEventListener("visibilitychange", function(e)
        {
            if (document.visibilityState == 'hidden')
            {
                console.log("beforeunload");
                location.reload();
            }
        });
    }
    else
    {
        window.addEventListener("beforeunload", function(e)
        {
            console.log("beforeunload");
        });
    }
    
    0 讨论(0)
  • 2020-11-28 11:52

    I realize I'm a bit late on this one, but I am dealing with this now, and I was thinking that something more like the following would be easier and more reliable. This is jQuery specific, but it should work with any system that allows you to bind and unbind events.

    $(window).bind('unload', function(){
        alert('unload event');
    });
    
    window.onbeforeunload = function(){
        $(window).unbind('unload');
        return 'beforeunload event';
    }
    

    This should unbind the unload event if the beforeunload event fires. Otherwise it will simply fire the unload.

    0 讨论(0)
  • 2020-11-28 11:56

    onbeforeunload is also supported by FF, so testing for browser won't help.

    0 讨论(0)
提交回复
热议问题