我有以下代码,如果他们刷新运行良好的页面,它将警告用户。
但是,当用户单击按钮或可能只是href='#'的内容,甚至是我的网站的URL更改时,他们也会收到警告。如何仅在他们尝试刷新浏览器时显示此警报?
谢谢
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'WARNING: You are about to reload this page, doing so will loose all your open tabs and loose any unsaved data.';
}
// For Safari
return 'WARNING: You are about to reload this page, doing so will loose all your open tabs and loose any unsaved data.';
};
概念解决方案(在jQuery中):
var going_away = true;
$("a").click(function()
{
// if it's local link - $(this).attr('href').indexOf("#") == 0 || $(this).attr('href').indexOf("/") == 0
going_away = false;
});
$("form").submit(function()
{
// if it's local action - $(this).attr('action').indexOf("/") == 0
going_away = false;
});
window.onbeforeunload = function (e) {
if (going_away)
window.confirm(...)
}
编辑:当然,条件的前提是针对传出链接,因此可能我们应该检查http或其他区分本地和传出链接的方法。