FAQ(Javascript) : User confirmation on close button of browser

Problem: On clicking the close button of browser ask for user confirmation with a custom message

Solution: Use the window.onbeforeunload method. This method expects a string value. This string will be displayed to user along with the default string. Default string that is displayed to user is:

Are you sure you want to navigate away from this page?
Press OK to continue, or Cancel to stay on the current page.

You can see an example in action here. Full code is given below.

<html>
<head>
<script type="text/javascript">
  window.onbeforeunload = function()
   { 
     return 'Please do not leave this page.'; 
   }
  
/*
alternatively, you can also write the following
this will also work the same as above 
window.onbeforeunload = confirmFromUser;
function confirmFromUser()
{
	return 'Please do not leave this page.';
}
*/

  
</script>
</head>
<body>
<p>
	Try reloading this page or closing your browser. <br/>
        Also try back, forward buttons.
</p>
<p>
	<a href="http://google.com">Click me</a>
</p>
</body>
</html>

onbeforeunload event will fire on reloading the page, using browser’s back/forward button or even on clicking an anchor that navigates user from current page to any other location.

4 thoughts on “FAQ(Javascript) : User confirmation on close button of browser

  1. Tapan

    Thank you very much Vijay. I have tried many many codes from dozens of sites but anyone not help me out as your code help me. Your code is same as i am searching on the net.
    Thanks again

    Reply
  2. Rohit

    Hello,
    I’m in need of a javascript which can catch closing of the browser. Actually onbeforeunload can catch it.But it also catches refresh and navigation of the page. I need to catch only the browser close. I need it for firefox 3.0 and IE 6&7 versions.

    i have a script based on the coordinates which can help in detecting close in IE. But it does not work for FIrefox. When we try to catch coordinates on Mouse events then it also doesn’t work.

    Please can you provide me javascript for firefox.
    Thanks.

    Reply
  3. Naresh Kumar

    Thanks i was googling so many sites i couldn’t find a right code, the code you provided is what i am looking for great stuff vijay.

    Cheers
    Naresh

    Reply

Leave a Reply