Javascript 离开网站时显示警告,而不仅仅是页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2365994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display a warning when leaving the site, not just the page
提问by tahdhaze09
This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible to display a dialog box when leaving a site?
当它呈现给我时,这听起来几乎是不可能做到的。我知道您可以在离开网页时显示一个对话框进行确认。但是离开站点时是否可以显示对话框?
I haven't been able to find/create anything that can read the address bar and know that you're leaving the site.
我无法找到/创建任何可以读取地址栏并知道您要离开该站点的内容。
回答by Robert Koritnik
First off define which events can actually take your user away from your site?
首先定义哪些事件实际上可以让您的用户离开您的网站?
- A click of a link inside your web site content
- A submit of a form to an outside action
- A javascript from a child window that changes window.location on its parent
- User starting a search in the search bar (FF and IE)
- User entering a search/address in the browser address bar.
- User hitting a back button (or backspace) when it just came to your site
- User hitting a forward button (or shift-backspace) when they were off the site before but came back by getting there via Back button functionality
- User closes the browser window
- 单击您网站内容中的链接
- 将表单提交给外部操作
- 来自子窗口的 javascript 更改其父窗口上的 window.location
- 用户在搜索栏中开始搜索(FF 和 IE)
- 用户在浏览器地址栏中输入搜索/地址。
- 用户刚来到您的网站时点击后退按钮(或退格)
- 用户之前离开网站时点击前进按钮(或 Shift-Backspace),但通过后退按钮功能回到那里
- 用户关闭浏览器窗口
So. what can you do about all these?
所以。你能做些什么呢?
- These are easy. Check your anchors and if they do point outside, add some functionality in the
onclickevent - Similar to 1. Add your functionality for the
onsubmitevent of the form posting back outside of your site. - -> 8. don't really have an applicable solution that could be controlled. You can abuse
onbeforeunloadevent as much as you want, but you won't have much success of knowing what's going on. And there are certain limitations related toonbeforeunloadas well, so your hands will be tied most of the time.
- 这些很容易。检查您的锚点,如果它们确实指向外部,请在
onclick事件中添加一些功能 - 类似于 1. 为
onsubmit表单回发到您的站点之外的事件添加您的功能。 - -> 8. 没有真正可以控制的适用解决方案。你可以
onbeforeunload随心所欲地滥用事件,但你不会成功地知道发生了什么。并且也有一些相关的限制onbeforeunload,所以你的手大部分时间都会被束缚。
The real question?
真正的问题?
Why would you want to control this event anyway except for bothering your users not to leave you. Begging doesn't give much justice in the web world anyway. And when some site would bother me with messages or even worse prevent mefrom leaving I wouldn't want to get back anymore. It smells of bad bad bad usability and gives a hint of adware site.
除了打扰您的用户不要离开您之外,您为什么还要控制此事件。无论如何,在网络世界中,乞讨并没有带来多少正义。当某些网站会用消息来打扰我,甚至更糟地阻止我离开时,我就不想再回来了。它闻起来有种糟糕的糟糕可用性,并暗示了广告软件网站。
Rather try to keep your users interestedby providing them with valuable content.
而是尝试通过向用户提供有价值的内容来保持他们的兴趣。
回答by BalusC
Your best bet is listening on the non-standard beforeunloadevent. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.
您最好的选择是收听非标准beforeunload事件。几乎所有浏览器都支持这一点,除了众所周知的 Opera 之外,它非常严格地遵守 W3C 标准。
Kickoff example:
开场示例:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
This message will show up in kind of a confirmation dialogue.
此消息将以确认对话框的形式显示。
In your specific case you need to turn it off (just set to null) whenever a navigational link is clicked or an internal form is submitted. You can do that by listening on the clickevent of the desired links and the submitevent of the desired forms. jQuerymay be of great help here:
在您的特定情况下,您需要在null单击导航链接或提交内部表单时将其关闭(只需设置为)。您可以通过监听click所需链接的submit事件和所需表单的事件来做到这一点。jQuery在这里可能会有很大帮助:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
You only need to give all external links the defacto standard attribute rel="ext"to denote that those are external links.
您只需要为所有外部链接提供事实上的标准属性rel="ext"来表示这些是外部链接。
<a href="http://google.com" rel="ext">Google</a>
回答by senerdude
This may help
这可能有帮助
- You need to check
onclickevent before attachinitLocalLinkException(); - Disclaimer: It's not tested.
- 您需要
onclick在附加之前检查事件initLocalLinkException(); - 免责声明:未经测试。
HTML:
HTML:
<a href="test.html">internal link</a>
<a href="#test">html anchor</a>
<a href="http://www.google.com">external link</a>
<a href="http://www.google.com" target="_blank">blank external link</a>
<form action="test.html" method="post" >
<button type="submit">Post Button</button>
</form>
JavaScript:
JavaScript:
$(document).ready(function () {
initLocalLinkException();
window.onbeforeunload = function () { confirmExit() };
$('form').submit(function () {
window.onbeforeunload = null;
});
});
function initLocalLinkException() {
$('a').click(function () {
if ($(this).attr('target') != '_blank') {
var link = $(this).attr('href');
if (link.substr(0, 4) == 'http') {
var LocalDomains = new Array('http://www.yourdomain.com',
'https://yourdomain.com',
'localhost', '127.0.0.1');
var matchCount = 0;
$.each(LocalDomains, function () {
if (this == link.substr(0, this.length)) {
matchCount++;
}
});
if (matchCount == '0') {
confirmExit();
} else {
window.onbeforeunload = null;
}
} else { window.onbeforeunload = null; }
}
});
}
function confirmExit() {
alert('Are you sure?'); // Do whatever u want.
}
回答by wsanville
Take a look at this thread.
看看这个线程。
One possible way to achieve this would be to use Javascript to examine all of the atags on your page when it loads and check if they are linking to an external site. If so, you can add an onclickevent to show a confirm/alert box or something more elegant. Of course, using jQuery will greatly simplify the Javascript you'll have to write, like in the above thread.
实现此目的的一种可能方法是使用 Javascripta在页面加载时检查页面上的所有标签,并检查它们是否链接到外部站点。如果是这样,您可以添加一个onclick事件来显示确认/警报框或更优雅的东西。当然,使用 jQuery 将大大简化您必须编写的 Javascript,就像在上面的线程中一样。
回答by Justin Johnson
Using the expression from this question, you can do the following:
使用此问题中的表达式,您可以执行以下操作:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
return obj.hostname == location.hostname;
};
$(function() {
var unloadMessage = function() {
return "Don't leave me!";
};
$('a:internal').click(function() {
window.onbeforeunload = null;
});
$('form').submit(function() {
window.onbeforeunload = null;
});
$('a:external').click(function() {
window.onbeforeunload = unloadMessage;
});
window.onbeforeunload = unloadMessage;
});
回答by dnagirl
It's possible. Just try entering a question or answer to SO and then navigating away before submitting it. It doesn't matter whether you click on a link or type in the address bar, you get an "Are you sure?" alert. You might post over on SO Metaasking how they do this.
这是可能的。只需尝试输入一个问题或对 SO 的回答,然后在提交之前导航离开。无论您是单击链接还是在地址栏中键入,您都会收到“您确定吗?” 警报。您可能会在SO Meta上发帖询问他们是如何做到的。
回答by Mic
You can do that if you design your site as a one page web app.
It means, a single page is loaded, then other contents are loaded dynamically using ajax.
如果您将网站设计为单页 Web 应用程序,您就可以做到这一点。
这意味着,加载单个页面,然后使用 ajax 动态加载其他内容。
In that case the onbeforeunloadis triggered when the user leave the page/site.
在这种情况下,onbeforeunload当用户离开页面/站点时触发。

