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

后端 未结 6 1287
别那么骄傲
别那么骄傲 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条回答
  •  萌比男神i
    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);
    }
    

提交回复
热议问题