使用 ASP.NET 中的母版页通过 onunload 函数捕获关闭浏览器

发布于 2024-11-15 04:04:26 字数 127 浏览 8 评论 0原文

我有一个带有母版页的网站。我想捕获尝试关闭浏览器/选项卡的用户。当我尝试在 body 标记中使用 onunload 时,它不仅在我尝试关闭浏览器时触发,而且在我导航到另一个页面时也会触发。

知道如何只捕获关闭浏览器的事件吗?

I have a website with master page. I want to catch a user trying to close the browser/tab. When I try using onunload in the body tag, it fires not only when I try closing the browser, but also when I navigate to another page.

Any idea how to only catch the event of closing the browser?

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

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

发布评论

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

评论(1

偏爱你一生 2024-11-22 04:04:26

您无法区分关闭浏览器和导航到另一个页面。在这两种情况下,当前页面都会被卸载。

更新:也许你可以用一些 jquery 处理某些情况,即每当单击链接时,设置一些标志以便能够将其与关闭窗口或输入新 URL 区分开来:

<body onunload="checkForClose()">

...

<script>
var _isNavigation = false;
$(document).ready(function () {
    // whenever a link is clicked set _isNavigation to true
    $('a').click(function () {
        _isNavigation = true;
    });
});

function checkForClose() {
    // show an alert if _isNavigation is not set
    if (!_isNavigation) alert("closing the browser (maybe)");
}
</script>

You can't distinguish closing the browser from navigating to another page. In both cases the current page is unloaded.

update: maybe you can handle some cases with some jquery, i.e. whenever a link is clicked, set some flag to be able to distinguish it from closing the window or entering a new URL:

<body onunload="checkForClose()">

...

<script>
var _isNavigation = false;
$(document).ready(function () {
    // whenever a link is clicked set _isNavigation to true
    $('a').click(function () {
        _isNavigation = true;
    });
});

function checkForClose() {
    // show an alert if _isNavigation is not set
    if (!_isNavigation) alert("closing the browser (maybe)");
}
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文