开发者

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

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 开发者_StackOverflow中文版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?


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜