javascript location.href onchange event listener?

半城伤御伤魂 提交于 2019-12-06 04:29:24

Here is a solution that works in all browsers. It uses the document.readyState attribute which works in all browsers except early versions FireFox (works in version 3.6.8). If the browser supports the readyState attribute it will check if the readyState is load (browser is going to another page) or is complete (or something else indicating that the page is not going anywhere). If the browser does not support the readyState then it will default to your solution.

(function(){
    var hideMessage=document.readyState?function(){
        setTimeout(function(){
            if(document.readyState=='loading'){
                hideMessage();
            }else{
                //hide message
            }
        },500);
    }:function(){
        // hide message
    }
    function displayMessage(){
        // display message
    }
    window.onbeforeunload=function(){
        displayMessage();
        setTimeout(hideMessage,document.readyState?10:5000);
    };
}());
Pekka supports GoFundMonica

As to the first point:

when the user presses Stop in the browser, cancelling the navigate-away action, I'd like the message to go away.

I had the same question a while back, and the resounding response - also backed by my subsequent research - was that this is impossible. Once you start a request for a new page, it's impossible to reliably "come back" from it programmatically. A timeout may indeed be the only way to go.

The two other points, though, should be relatively straightforward: Walk through every link (e.g. using jQuery), and add a click event that opens the confirmation window, and returns false so that the original href isn't opened. It should also be relatively easy to do this for internal links only (check for the target property, if it's _blank, leave the link alone.)

It may become tough to deal with links that already have click events, though, and other events leading to a different page like form submissions.

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