Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript addEventListener不使用onbeforeunload_Javascript_Events_Google Chrome_Addeventlistener_Onbeforeunload - Fatal编程技术网

Javascript addEventListener不使用onbeforeunload

Javascript addEventListener不使用onbeforeunload,javascript,events,google-chrome,addeventlistener,onbeforeunload,Javascript,Events,Google Chrome,Addeventlistener,Onbeforeunload,^这似乎不起作用。。。完全页面将直接关闭,而不显示确认框 我意识到 window.addEventListener("onbeforeunload",function() {return "are you sure?"}); 将工作,但我想添加到功能中(例如,将许多事件侦听器添加到“onbeforeunload”函数),而不是完全重写该函数 在卸载之前从on中删除on 另外,请注意,addEventListener在较旧的IE浏览器和可能的其他浏览器中不起作用。如果您想要一致的事件绑定,请使用

^这似乎不起作用。。。完全页面将直接关闭,而不显示确认框

我意识到

window.addEventListener("onbeforeunload",function() {return "are you sure?"});

将工作,但我想添加到功能中(例如,将许多事件侦听器添加到“onbeforeunload”函数),而不是完全重写该函数

在卸载之前从
on
中删除
on

另外,请注意,
addEventListener
在较旧的IE浏览器和可能的其他浏览器中不起作用。如果您想要一致的事件绑定,请使用库。

Mozila开发者网络有一个“几乎跨浏览器的工作示例”。使用他们的代码

2014年,这是 到2020年,它现在是 所有这些? 如果我需要这个,我会把工作委托给图书馆。如果我必须自己做这件事,我想人们可以做以上所有的事情,只是为了更加确定

  • 不要试图设置有意义的消息文本,它只会给出不一致的UX
  • event=event | | window.event
  • event.preventDefault()
    ,可能在检查是否定义了preventDefault之后
  • event.returnValue=''
  • 返回“”

事件监听器的上没有前缀
,但它是适用的,或者我可以说是事件处理程序所必需的

所以,请记住

EventHandlers=上的前缀

EventListeners=前缀关闭


这是addEvent的跨浏览器解决方案:
函数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);)。这在最新的FF-14.0.1中似乎不起作用anymore@Marcin仅仅返回字符串已经不够了。您必须设置
event.returnValue
()为什么不再工作?浏览器改变了吗?我使用的是:
window.addEventListener(“beforeunload”,()=>{return'Stop')无论我采用哪种方式,都无法自定义message@toddmo现在,浏览器不显示自定义消息。这是一个安全/用户体验功能。看见或者链接到那里的MDN页面。这是在写了答案之后出现的。谢谢,我终于也看到了:)现在你似乎不应该放return语句,只要放
e.returnValue=随便什么@ivkremer不。如今,正如托德莫所发现的,你不会收到定制的消息。在过去,您会为某些浏览器设置
e.returnValue
,为其他浏览器设置
return
消息字符串。(好吧,两种方法都可以,但只有一种会产生效果,具体取决于使用的浏览器,而另一种则会被忽略)
window.onbeforeunload = function() {return "are you sure?"}
window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
});
window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});