addEventListener无法使用onbeforeunload

zco*_*y13 16 javascript events google-chrome onbeforeunload addeventlistener

window.addEventListener("onbeforeunload",function() {return "are you sure?"});
Run Code Online (Sandbox Code Playgroud)

^这似乎不起作用... ...页面将关闭而不显示确认框...

我意识到......

window.onbeforeunload = function() {return "are you sure?"}
Run Code Online (Sandbox Code Playgroud)

会工作,但我想添加功能(例如添加许多事件监听器到"onbeforeunload"功能)不完全重写功能!

med*_*iev 27

取出ononbeforeunload.

另外,请注意,addEventListener在旧版IE和其他浏览器中无法使用.如果您想要一致的事件绑定,请使用库.

  • 以下是addEvent的跨浏览器解决方案:`function addEvent(evt,fn,useCapture){if(this.addEventListener){this.addEventListener(evt,fn,useCapture); return true;} else if(this.attachEvent) {var r = this.attachEvent('on'+ evt,fn); return r;} else this ['on'+ evt] = fn;} Object.prototype.addEvent = addEvent;`(写这样的函数: object.addEvent(event,function,useCapture);). (2认同)
  • 这似乎不再适用于最新的FF-14.0.1 (2认同)

use*_*610 16

在Mozila Developer Network API参考中有一个"几乎跨浏览器的工作示例",用于beforeunload事件.使用他们的代码.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
});
Run Code Online (Sandbox Code Playgroud)