Rob Rob - 2 years ago 211
Javascript Question

onbeforeunload not working in Windows Chrome

I have seen this issue posted before but onbeforeunload does not work for me in Windows Chrome. I am using version 49.0.2623.112 m. Here is my code:

<body onbeforeunload="handleBrowserCloseButton();">

function handleBrowserCloseButton() {

//Call method by Ajax call
alert('Browser close button clicked');


When I navigate away from the page or close the browser window, nothing happens. Any help would be greatly appreciated.

Answer Source

You need to return a non-void value from the callback function, otherwise you won't see a message dialog.

So you would need to change two things:

<body onbeforeunload="return handleBrowserCloseButton();">


function handleBrowserCloseButton() { 
    return 'Browser close button clicked';

Beside that you should use window.addEventListener('beforeunload', ... ) instead.

MDN: WindowEventHandlers.onbeforeunload: Notes:

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog. In Firefox 4 and later the returned string is not displayed to the user. Instead, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." See bug 588292.

Because the functionality should net be misused to prevent the user form leaving the page, functions like alert or confirm won't work in the onbeforeunload callback.

MDN: WindowEventHandlers.onbeforeunload: Notes:

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download