Search code examples
jqueryonbeforeunload

beforeunload on Chrome


I have this code that will redirect the user to another URL whenever he/she closes the page. This is working on Firefox, IE, Safari, etc. but not in Chrome. It won't redirect the user to new URL.

Thanks!

jQuery(document).ready(function() { 
    jQuery(window).bind('beforeunload', function(e) {  
        location.href="http://google.com/";
        return "Before you leave, please take a look at this limited time offer.";
    });
});

Solution

  • Not sure it is what you are looking for, this will redirect user if he choices to stay on page:

    DEMO

    var a,b;
    window.onbeforeunload = function (e) {
        if (b) return;
        a = setTimeout(function () {
            b = true;
            window.location.href = "http://google.com";
        }, 500);
        return "Before you leave, please take a look at this limited time offer.";
    }
    window.onunload = function () {
        clearTimeout(a);
    }