vijayjoshi.org - php | javascript | ajax | and all things web

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.

Related Posts

Posted in : FAQ, Javascript
Tags:

2 Comments to “FAQ(Javascript) : User confirmation on close button of browser”

Add Comments (+)

  1. Tapan says:

    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

  2. Rohit says:

    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.

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

55,788 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>