Search code examples
javascriptjquerycross-browseronbeforeunload

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


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.


Solution

  • 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.