简体   繁体   中英

Why the browsers confirm box (triggered by beforeunload event handler) only appears when I click onto the page?

I would like to display a confirm box and warn the user, before he leaves the page, especially during an HTTP request. To this end, I added an event listener to the window object within my react component.

  componentWillMount() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  }

  componentWillUnmount() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  }

  handleBeforeUnload(e) {
    e.returnValue = 'You sure you want to leave?';
  }

This snippet works and makes our life easier but there's one thing that piqued my curiosity.

I see the confirm box, only if I click onto the page after loading. It does not display the browsers native confirm box, although it triggers the handleBeforeUnload method.

Could someone explain, why window.onbeforeunload works only if I focus into the page?

This is an intentional limitation. From MDN:

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.

See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM