简体   繁体   English

为什么当我单击页面时,浏览器的确认框(由beforeunload事件处理程序触发)才出现?

[英]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. 我想在用户离开页面之前,特别是在HTTP请求期间,显示一个确认框并警告用户。 To this end, I added an event listener to the window object within my react component. 为此,我将一个事件侦听器添加到了我的react组件内的window对象。

  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. 尽管它会触发handleBeforeUnload方法,但它不会显示浏览器的本机确认框。

Could someone explain, why window.onbeforeunload works only if I focus into the page? 有人可以解释一下,为什么window.onbeforeunload仅在我专注于页面时才起作用?

This is an intentional limitation. 这是有意的限制。 From MDN: 从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. 注意:为避免意外弹出窗口,除非页面已与之交互,否则浏览器可能不会显示在beforeunload事件处理程序中创建的提示,甚至根本不会显示它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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