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

后端 未结 6 1296
别那么骄傲
别那么骄傲 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: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;
    

提交回复
热议问题