I tried the following code to get an alert upon closing a browser window:
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert. I need to show the alert only when I close the browser window and not upon clicking hyperlinks.
Keep your code as is and use jQuery to handle links:
Another implementation is the following you can find it in this webpage: http://ujap.de/index.php/view/JavascriptCloseHook
What it does is you use a variable as a flag.
You can detect hyperlinks clicks, but you can't determine whether user:
All these actions generate
beforeunload
event onwindow
, without any more exact information about the event.In order to display confirmation dialog when doing above actions, and not display it when a hyperlink was clicked, follow these steps:
beforeunload
event listener towindow
, which returns confirmation text as a string, unless a specific variable (flag) is set totrue
.click
event todocument
. Check ifa
element has been clicked (event.target.tagName
). If yes, set flag totrue
.You should also handle form submissions by assigning a
submit
event listener todocument
.Your code could look like this:
Note that in some browsers you have to use
event.returnValue
inbeforeunload
listener, and in others you usereturn
statement.See also
beforeunload
event docs.