【问题标题】:addEventListener not working with onbeforeunloadaddEventListener 不适用于 onbeforeunload
【发布时间】:2012-06-10 19:08:57
【问题描述】:
window.addEventListener("onbeforeunload",function() {return "are you sure?"});

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

我意识到...

window.onbeforeunload = function() {return "are you sure?"}

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

【问题讨论】:

    标签: javascript events google-chrome addeventlistener onbeforeunload


    【解决方案1】:

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

    在 2014 年,那是

    window.addEventListener("beforeunload", function (e) {
      var confirmationMessage = "\o/";
    
      (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
      return confirmationMessage;                                //Webkit, Safari, Chrome etc.
    });
    

    2020年,现在是

    window.addEventListener('beforeunload', (event) => {
      // Cancel the event as stated by the standard.
      event.preventDefault();
      // Chrome requires returnValue to be set.
      event.returnValue = '';
    });
    

    以上所有?

    如果我需要这个,我想把这项工作委托给图书馆。如果我必须自己做,我想一个人可以做到以上所有,只是为了更加确定

    • 不要尝试设置有意义的消息文本,它只会给出不一致的用户体验
    • event = event || window.event
    • event.preventDefault(),也许在检查 preventDefault 是否已定义之后?
    • event.returnValue = ''
    • return ''

    【讨论】:

    • 无论如何我都无法自定义消息
    • @toddmo 如今,浏览器不显示自定义消息。这是一个安全/用户体验功能。见chromestatus.com/feature/5349061406228480。或那里的链接 MDN 页面。这是写完答案后出现的。
    • 谢谢,我终于也看到了:)
    • 现在看来你不应该写return语句,只写e.returnValue = whatever;
    • @ivkremer 不。如今,正如 toddmo 发现的那样,您不会收到自定义消息。在过去,您会为某些浏览器设置e.returnValue,而为其他浏览器设置return 消息字符串。 (好吧,你可以两者都做,但只有一个会产生效果,具体取决于使用的浏览器,而另一个会被忽略)
    【解决方案2】:

    EventListeners 没有前缀 on,但它适用,或者我可以说对于 EventHandlers

    是必要的

    所以,请记住这一点

    EventHandlers = 前缀

    EventListeners = 前缀关闭

    【讨论】:

      【解决方案3】:

      onbeforeunload 中删除on

      另外,请注意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);)。
      • 这似乎不再适用于最新的 FF - 14.0.1
      • @Marcin 仅仅返回一个字符串是不够的。你必须设置event.returnValue (doc)
      • 为什么这不再有效?浏览器变了吗?我正在使用这个:window.addEventListener("beforeunload",() => {return 'Stop')};
      猜你喜欢
      • 2014-01-29
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      相关资源
      最近更新 更多