1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Greg Oks
  • 2,700
  • 4
  • 35
  • 41
  • This question is completely independent of the server-side technology. Maybe remove the asp.net and masterpage tags? – M4N Jun 09 '11 at 10:25
  • The onunload function works fine when there is only page. It's completely different story when there is master page and there is a confusion with closing the browser or just redirecting to another page. So I wanted to be clear with my question and what do I mean exactly. – Greg Oks Jun 09 '11 at 10:30
  • [Check this](http://stackoverflow.com/questions/1889404/jquery-ui-dialog-onbeforeunload/1889450#1889450) – Yuriy Rozhovetskiy Jun 09 '11 at 10:26

1 Answers1

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>
M4N
  • 94,805
  • 45
  • 217
  • 260
  • is that correct? at least chrome and firefox distinguishes them. test. type something in the textbox below and try to close the browser. you will get an alert. now navigate to another tab. no warning occurs. – naveen Jun 09 '11 at 10:15
  • Navigating to another tab is something completely different. It has no effect on the current page (it is not unloaded). – M4N Jun 09 '11 at 10:17