using onbeforeunload event, url change on selecting stay on this page

后端 未结 6 1265
别那么骄傲
别那么骄傲 2020-11-29 06:03

Rewriting the question -

I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the on

相关标签:
6条回答
  • 2020-11-29 06:32

    Try the following, (adds a global function that checks the state all the time though).

    var redirected=false;
    $(window).bind('beforeunload', function(e){
        if(redirected)
            return;
        var orgLoc=window.location.href;
        $(window).bind('focus.unloadev',function(e){
            if(redirected==true)
                return;
            $(window).unbind('focus.unloadev');
            window.setTimeout(function(){
                if(window.location.href!=orgLoc)
                    return;
                console.log('redirect...');
                window.location.replace('http://google.com');
            },6000);
            redirected=true;
        });
        console.log('before2'); 
        return "okdoky2";
    });
    
    $(window).unload(function(e){console.log('unloading...');redirected=true;});
    
    0 讨论(0)
  • 2020-11-29 06:32

    I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...

    Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)

    Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

    0 讨论(0)
  • 2020-11-29 06:37

    After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.

    jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN

    var F = function(){}; // empty function
    var offerUrl = 'http://bing.com';
    var url;
    
    
    var handler = function(e) {
        timeout = setTimeout(function () {
            console.log('location.assign');
            location.assign(offerUrl);
    
        /*
         * This value makes or breaks it.
         * You need enough time so the browser can make the connection to
         * the clicked links href else it will still redirect to the offer url.
         */
        }, 1400);
    
        // important!
        window.onbeforeunload = F;
    
        console.info('handler');
        return 'Do you wan\'t to leave now?';
    };
    
    window.onbeforeunload = handler;
    
    0 讨论(0)
  • 2020-11-29 06:44

    It's better to Check it local.
    Check out the comments and try this: LIVE DEMO

    var linkClick=false; 
    document.onclick = function(e)
    {
        linkClick = true;
        var elemntTagName = e.target.tagName;
        if(elemntTagName=='A')
        {
            e.target.getAttribute("href");
            if(!confirm('Are your sure you want to leave?'))
            {
               window.location.href = "http://google.com";
               console.log("http://google.com");
            }
            else
            {
                window.location.href = e.target.getAttribute("href");
                console.log(e.target.getAttribute("href"));
            }
            return false;
        }
    }
    function OnBeforeUnLoad () 
    {
        return "Are you sure?";
        linkClick=false; 
        window.location.href = "http://google.com";
        console.log("http://google.com");
    }
    

    And change your html code to this:

    <body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
        <a href="http://yahoo.com">try it</a>
    </body>
    
    0 讨论(0)
  • 2020-11-29 06:44
    <script>
            function endSession() {
                // Browser or Broswer tab is closed
                // Write code here
                alert('Browser or Broswer tab closed');
            }
    </script>
    
    <body onpagehide="endSession();">
    
    0 讨论(0)
  • 2020-11-29 06:45

    This solution works in all cases, using back browser button, setting new url in address bar or use links. What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler. In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)

    http://jsfiddle.net/W3vUB/4/show

    http://jsfiddle.net/W3vUB/4/

    EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!) BTW, using bing.com due to google not allowing no more content being displayed inside iframe.

    http://codepen.io/anon/pen/dYKKbZ

    var a, b = false,
        c = "http://bing.com";
    
    function triggerEvent(el, type) {
        if ((el[type] || false) && typeof el[type] == 'function') {
            el[type](el);
        }
    }
    
    $(function () {
        $('a:not([href^=#])').on('click', function (e) {
            e.preventDefault();
            if (confirm("Do you really want to leave now?")) c = this.href;
    
    
            triggerEvent(window, 'onbeforeunload');
    
        });
    });
    
    window.onbeforeunload = function (e) {
        if (b) return;
        a = setTimeout(function () {
            b = true;
            window.location.href = c;
            c = "http://bing.com";
            console.log(c);
        }, 500);
        return "Do you really want to leave now?";
    }
    window.onunload = function () {
        clearTimeout(a);
    }
    
    0 讨论(0)
提交回复
热议问题