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

送分小仙女□ 提交于 2019-11-28 10:12:31

问题


After a long day of trying to find a solution to this problem, I keep getting the same issue.

Basically, I have a site, if the user clicks on the "browser-refresh" button, I want to pop-up a "are you sure" alert box with the options "reload" and "don't reload" (Basically, what the browser returns).

Surprisingly, it works just fine in IE. But in chrome or firefox, the refresh happens normally without a popup.

The popup only appears if I click on the body some where and then click on the "browser-refresh" button.

I already the following and other many similar alternatives :

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';
};

I tried to simulate a click event on page load with 'trigger('click')', '.click()' events.

But, still doesn't work until I click on the body myself (physically).

I've created a short pen, which replicates the issue I'm facing.

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

Any help would be very highly appreciated. Thanks in Advance.


回答1:


Maybe a late answer...

Here is what MDN documentation on beforeunload event states:

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.

This matches the behavior you observed.



来源:https://stackoverflow.com/questions/48523454/onbeforeunload-doesnt-work-until-mouse-is-clicked-once-in-the-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!