Beforeunload无法将用户重定向到另一个页面,当用户试图关闭窗口/选项卡时,我如何将其重定向到其他页面/url

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?

本文关键字:重定向 用户 选项 其他 url 另一个 Beforeunload 窗口      更新时间:2023-09-26

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

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

我希望用户在尝试关闭选项卡时重定向到另一个页面。实现这一目标的替代和适当方式是什么?

*不要这样做*

但有了用户的许可,这是可能的;你可以实现这样的事情(花了我一段时间才找到一个在框架中快乐的网站)

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
}

演示

我认为这是不可能的。

在这次活动中,你可以做一些事情,但由于当时的垃圾邮件发送者,这一点受到了严重限制。他们过去在窗口状态栏中有动画文本,这会模糊链接href,所以当你试图离开时,你会盲目点击并打开大量窗口,所以你基本上被困在了网站上。

这是一个如此严重的问题,据我回忆,这是Firefox首次推出时吹嘘要解决的"功能"之一。

它被淡化为能够恳求他们留在对话框中,但后来被滥用,因为人们把它写成了官方系统的信息,并欺骗了人们。

现在,大多数浏览器都允许你请求"停留在页面上/离开页面"对话框,但不允许你控制措辞。

以下是一些列出您选项的文档:

  • https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload