Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beforeunload is not working to redirect user to another page, how can I redirect user to another page/url when he attempts to close a window/tab?

My following code isn't working to redirect the user to another page:

$(window).on('beforeunload',function(){
                        window.location.href="http://www.google.com;
                    }) ;

I want the user to be redirected to another page when he attempts to close the tab. What's the alternative and appropriate way to achieve this?

like image 517
Umer Hassan Avatar asked Jan 29 '26 20:01

Umer Hassan


1 Answers

*Don't do it*

But it is possible with the user's permission; you can achieve something like this (took me a while to find a website that was happy in a frame)

window.onbeforeunload = function () {
    window.setTimeout(function () { // escape function context
        window.location = 'http://bbc.co.uk';
    }, 0);
    window.onbeforeunload = null;   // necessary to prevent infinite loop
                                    // that kills your browser
    return 'Press "Stay On Page" to go to BBC website!';
        // pressing leave will still leave, but the GET may be fired first anyway
}

Demo

like image 58
Paul S. Avatar answered Jan 31 '26 08:01

Paul S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!