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.

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

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

  1. 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. 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.

  3. 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.


Leave a Reply