使用 JavaScript 防止网页导航离开

发布于 2024-07-19 06:56:55 字数 32 浏览 7 评论 0原文

如何使用 JavaScript 防止网页导航离开?

How to prevent a webpage from navigating away using JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

旧伤还要旧人安 2024-07-26 06:56:55

使用 onunload 允许您显示消息,但不会中断导航(因为为时已晚)。 但是,使用 onbeforeunload 将中断导航:

window.onbeforeunload = function() {
  return "";
}

注意:会返回空字符串,因为较新的浏览器会提供一条无法覆盖的消息,例如“任何未保存的更改都将丢失”。

在旧版浏览器中,您可以指定在提示中显示的消息:

window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
}

Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:

window.onbeforeunload = function() {
  return "";
}

Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.

In older browsers you could specify the message to display in the prompt:

window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
}
小清晰的声音 2024-07-26 06:56:55

使用现代的 addEventListener API 以更现代且与浏览器兼容的方式进行等效操作。

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

来源:https://developer.mozilla.org/en-US/docs /Web/Events/卸载前

The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

你是我的挚爱i 2024-07-26 06:56:55

与此处介绍的其他方法不同,这段代码不会导致浏览器显示警告,询问用户是否要离开; 相反,它利用 DOM 的事件性质在浏览器有机会从内存中卸载页面之前重定向回当前页面(从而取消导航)。

由于它是直接短路导航来工作的,所以不能用来防止页面关闭; 但是,它可用于禁用帧破坏。

(function () {
    var location = window.document.location;

    var preventNavigation = function () {
        var originalHashValue = location.hash;

        window.setTimeout(function () {
            location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
            location.hash = originalHashValue;
        }, 0);
    };

    window.addEventListener('beforeunload', preventNavigation, false);
    window.addEventListener('unload', preventNavigation, false);
})();

免责声明:您绝对不应该这样做。 如果页面上有框架破坏代码,请尊重作者的意愿。

Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.

Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.

(function () {
    var location = window.document.location;

    var preventNavigation = function () {
        var originalHashValue = location.hash;

        window.setTimeout(function () {
            location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
            location.hash = originalHashValue;
        }, 0);
    };

    window.addEventListener('beforeunload', preventNavigation, false);
    window.addEventListener('unload', preventNavigation, false);
})();

Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.

誰認得朕 2024-07-26 06:56:55

我最终得到了这个略有不同的版本:

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

在其他地方,当表单变脏时,我将脏标志设置为 true(或者我想防止导航离开)。 这使我可以轻松控制用户是否收到确认导航提示。

对于所选答案中的文本,您会看到多余的提示:

在此处输入图像描述

I ended up with this slightly different version:

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.

With the text in the selected answer you see redundant prompts:

enter image description here

べ繥欢鉨o。 2024-07-26 06:56:55

在艾曼的示例中,通过返回 false 可防止浏览器窗口/选项卡关闭。

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}

In Ayman's example by returning false you prevent the browser window/tab from closing.

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}
木緿 2024-07-26 06:56:55

相当于 jQuery 1.11 中接受的答案:

$(window).on("beforeunload", function () {
    return "Please don't leave me!";
});

JSFiddle 示例

altCognito 的答案使用了 unload事件,该事件发生得太晚,JavaScript 无法中止导航。

The equivalent to the accepted answer in jQuery 1.11:

$(window).on("beforeunload", function () {
    return "Please don't leave me!";
});

JSFiddle example

altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.

一城柳絮吹成雪 2024-07-26 06:56:55

该建议的错误消息可能会与浏览器已显示的错误消息重复。 在 Chrome 中,2 个类似的错误消息会在同一窗口中相继显示。

在 Chrome 中,自定义消息后显示的文本是:“您确定要离开此页面吗?”。 在 Firefox 中,它根本不显示我们的自定义错误消息(但仍然显示对话框)。

更合适的错误消息可能是:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

或者 stackoverflow 风格:“您已经开始编写或编辑帖子。”

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

Or stackoverflow style: "You have started writing or editing a post."

依 靠 2024-07-26 06:56:55

如果您遇到浏览器后退/前进按钮并且不想离开,您可以使用:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

否则,您可以使用beforeunload 事件,但该消息可能会或可能不会跨浏览器工作,并且需要返回强制内置提示的内容。

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

随梦而飞# 2024-07-26 06:56:55

使用 onunload

对于 jQuery,我认为它的工作方式如下:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});

Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});
苏辞 2024-07-26 06:56:55

如果您需要在退出时将状态切换回通知,请使用以下行:

window.onbeforeunload = null;

If you need to toggle the state back to no notification on exit, use the following line:

window.onbeforeunload = null;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文