【问题标题】:.beforeunload only working on refresh.beforeunload 仅适用于刷新
【发布时间】:2017-04-12 13:55:14
【问题描述】:

如果有任何未保存的信息,我试图在用户转到应用内的另一个页面之前提醒他们。我正在听从several stackoverflows 的建议使用.beforeunload 但它仅在我刷新页面时才有效,而不是在我单击指向站点上另一个页面的链接时。我误解了如何使用 beforeunload 还是我需要另一个事件监听器?

应用程序.js

//= require forms.js

forms.js

$(window).on('beforeunload', function () {
    console.log('unloading')
});

【问题讨论】:

  • 当您单击链接转到另一个站点/页面时,它应该会触发。
  • @epascarello 当您转到网站上的另一个页面时它不会。有什么想法吗?
  • 所以你有它以便在页面导航发生时保留日志?我们在这里处理的是什么浏览器?
  • @epascarello 我目前正在使用 chrome。
  • 很可能当您转到您网站上的另一个页面时,您实际上并没有转到另一个页面。您必须使用自定义对话框将此功能与处理“页面更改”的任何内容联系起来。

标签: javascript jquery onbeforeunload


【解决方案1】:

beforeunload 事件的工作方式如下:

    // Fires just before leaving/refreshing the page.  Handler will
    // be passed the event object and if a returnValue is set on the 
    // event, the browser will display a confirmation dialog with the
    // returnValue message displayed.
    window.addEventListener("beforeunload", function (evt) {
      evt.returnValue = "Setting this to anything but an empty string, causes this to work!";
    }, false);

有关示例,请参阅 this Fiddle

【讨论】:

  • @epascarello 她没有在事件对象上设置returnValue。正如我的 cmets 所指出的那样。
  • 它应该按照 OP 的方式正常工作,你可以在没有 returnValue 的情况下触发内部的东西。
  • @epascarello 不正确:developer.mozilla.org/en-US/docs/Web/Events/beforeunload 将字符串分配给 returnValue 事件属性时,会出现一个对话框,要求用户确认离开页面(参见下面的示例)。 当没有提供值时,事件被静默处理。
  • 我可以读到:当没有提供值时,事件会被静默处理。”这意味着它在没有对话框的情况下运行。这并不意味着跳过里面的代码.
  • @gwalshington 以jsfiddle.net/9L7kte3k/4为例。
猜你喜欢
  • 2021-08-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 2015-12-24
  • 1970-01-01
相关资源
最近更新 更多