问题描述
我正在努力让这个Javascript正常运行。我的意图是,当用户试图关闭网站页面以获得停留在当前页面或关闭的警报时如果他们点击确定我希望它关闭,如果他们点击取消我希望它重定向到另一页。问题是,当他们试图转到同一网站上的另一个页面时,它会给他们弹出窗口。我希望它仅在关闭时显示,而不是在将页面离开到另一页时显示。我不确定这是否可行,我非常感谢您的帮助和评论。
I'm trying to get this Javascript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.
window.onbeforeunload = fget;
function yPop(url) {
var found = 1;
window.onbeforeunload = '';
window.location = url;
return false;
}
function fget() {
alert("Thank you for visiting our website, you are welcome any time! \n\n");
window.location = "http://NewLink.com";
return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
推荐答案
-
不要这样做。
Don't do this.
您无法仅检测到关闭,但您可以通过单击内部链接和其他类型的离开来区分离开,包括外部链接,后退按钮,关闭并选择/输入新的URL。在页面加载后的脚本中,设置onbeforeunload事件,然后扫描所有document.links并针对当前location.host测试他们的.host。如果匹配,则为内部链接。在这种情况下,向他们添加一个onclick事件,在返回true之前删除onbeforeunload事件,允许链接在没有警告的情况下正常运行。
You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.
认真地,不要这样做。这令人难以置信的刺激,傲慢和无用。使用离开pester脚本的网站管理员被谴责到第四个互联网地狱圈,他们必须花费剩下的永恒时间,只使用 ed ,一个磨损的牙刷和一个< layer> -tag。
Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.
这篇关于Javascript在关闭浏览器窗口时获取重定向警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!