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
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.


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