Search code examples
javascriptpopupalertonbeforeunload

Overriding native Javascript alert function to capture onbeforeunload alerts


My question is not about how to override the alert function and then decorate it as you want. My problem is that when you override the alert function like this:

window.alert = function(str){console.log('alert is called: '+ str);}

For a page with a registered handler for onbeforeunload event like this:

window.onbeforeunload= function(){return 'bye!';}
It is supposed to pop up an alert box with the string "bye" before leaving a page and you could catch it using your custom alert function. But the problem is that your custom alert function won't be called in this case. It looks like the browser is calling another alert function to put your string there. How can I override that alert function?


Solution

  • According to MSDN

    Remarks When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current document and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

    this is not an alert, it is a confirm box which browser provides and we can not alter that. please find the link https://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx