Beforeunload无法将用户重定向到另一个页面,如何在尝试关闭窗口/选项卡时将用户重定向到另一个页面/ URL?

问题描述:

我的以下代码无法将用户重定向到另一个页面:

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?

* 不要这样做 *



但是有可能获得用户的许可;你可以做到这样的事情(花了一些时间找到一个框架中很开心的网站)

*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
}

演示