覆盖本机 Javascript 警报功能以捕获 onbeforeunload 警报

Overriding native Javascript alert function to capture onbeforeunload alerts

我的问题不是关于如何覆盖警报功能,然后根据需要对其进行装饰。我的问题是,当您像这样覆盖警报功能时:

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

对于像这样注册了 onbeforeunload 事件处理程序的页面:

window.onbeforeunload= function(){return 'bye!';}
它应该在离开页面之前弹出一个带有字符串 "bye" 的警告框,您可以使用自定义警告功能捕获它。但问题是在这种情况下不会调用您的自定义警报功能。看起来浏览器正在调用另一个警报函数来将您的字符串放在那里。我如何覆盖该警报功能?

根据 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.

这不是警告,这是浏览器提供的确认框,我们无法更改。请找到 link https://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx