Javascript,我可以“重定向"吗?用户在 onbeforeunload ?如果不能,如何 [英] Javascript, Can I "redirect" user in onbeforeunload? If cant, how to
问题描述
是否可以在用户关闭浏览器时重定向到另一个页面?
Is it possible to redirect to another page when the user closes the browser?
尝试:
我试过onunload,不行
I tried onunload, does not work
window.onunload = function redirect(){...}
我也试过另一种方法,它也不起作用:
I also tried another method, it doesn't work either:
window.onbeforeunload = redirect(){...}
第三种方法,我想取消onbeforeunload
(表示延迟关闭浏览器),我调用重定向函数,window.confirm
,如果是redirect,如果没有则关闭浏览器.但效果不佳.
The 3rd method, I want to cancel the onbeforeunload
(means delay closing the browser), the I call the redirect function, window.confirm
, if yes redirect, if no then close the browser. But it does not work as well.
还有什么办法吗??也许提示让用户选择是否在他/她关闭浏览器时重定向到新页面?我的想法快用完了...
Is there any other way?? Maybe prompt to let user select whether to redirect to new page when he/she close the browser? I'm running out of ideas...
推荐答案
你的 onbeforeunload 事件需要返回一个字符串(不等于 false),浏览器会在它自己显示给用户的消息中包含这个字符串.
Your onbeforeunload event needs to return a string (that doesn't equate to false), the browser will include this string in its own message displayed to the user.
window.onbeforeunload = function(){
location.assign('http://www.google.com');
return "go to google instead?";
}
但是,以用户能够理解要做什么的方式来表达您的消息将非常棘手.而且我不确定这在每个浏览器中是否都很强大,我只是在 Chrome 中尝试过,它有效,但我最终得到了一个无法关闭的选项卡!谢天谢地,我设法通过 Chrome 任务管理器杀死了它.
However, it's going to be really tricky to word your message in a way that the user would be able to understand what to do. And I'm not sure this is robust in every browser, I just tried it in Chrome, it worked, but I ended up with a tab I could not close! I managed to kill it via the Chrome task manager thankfully.
这篇关于Javascript,我可以“重定向"吗?用户在 onbeforeunload ?如果不能,如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!