catch close browser with onunload function using master page in ASP.NET

放肆的年华 提交于 2019-12-11 07:33:55

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/6291178/catch-close-browser-with-onunload-function-using-master-page-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!