在 body 中单击鼠标一次后,Onbeforeunload 才会工作

Onbeforeunload doesn't work until mouse is clicked once in the body

经过漫长的一天尝试找到解决此问题的方法后,我不断遇到同样的问题。

基本上,我有一个网站,如果用户点击 "browser-refresh" 按钮,我想 pop-up 一个带有选项 "reload" 和"don't reload"(基本上就是什么浏览器returns)。

令人惊讶的是,它在 IE 中工作得很好。但在 chrome 或 firefox 中,刷新正常发生而没有弹出窗口。

仅当我在某个位置单击 body 然后单击 "browser-refresh" 按钮时才会出现弹出窗口。

我已经有了以下和其他许多类似的选择:

window.onbeforeunload = function (e) {
    e = e || window.event;

   // For IE and Firefox prior to version 4
   if (e) {
       e.returnValue = 'Any string';
   }

  // For Safari
  return 'Any string';
};

我尝试使用“trigger('click')”、“.click()”事件模拟页面加载时的点击事件。

但是,在我自己(物理上)点击 body 之前,仍然无法正常工作。

我创建了一支短笔,它复制了我面临的问题。

https://codepen.io/kanchanrai/pen/LQEZYV

如有任何帮助,我们将不胜感激。提前致谢。

也许回答晚了...

MDN documentation on beforeunload event 的内容如下:

Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

这与您观察到的行为相符。