[Electron] Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had...

前提:chrome60以后,如果用户打开浏览器后没有任何交互,直接关闭网页,则不会触发beforeunload事件 https://www.chromestatus.com/feature/5082396709879808

问题:electron中,当浏览器窗口关闭时触发beforeunload事件,并在beforeunload事件中添加event.returnValue = "";试图阻止浏览器关闭时,并未如期出现 以下弹框:
image.png

原因:https://electronjs.org/docs/api/web-contents#event-will-prevent-unload
'will-prevent-unload' Emitted when a beforeunload event handler is attempting to cancel a page unload.因此浏览器的beforeunload事件会被electron的will-prevent-unload事件捕获,当beforeunload事件发生时,我们可以在electron中添加will-prevent-unload事件的处理:

  win.webContents.on('will-prevent-unload', (event) => {
      const choice = dialog.showMessageBox(winMain, {
        type: 'question',
        buttons: ['离开', '取消'],
        title: '离开此网站?',
        message: '系统可能不会保留您所做的更改。',
        defaultId: 0,
        cancelId: 1
      })
      const leave = (choice === 0)
      if (leave) {
        event.preventDefault()
      }
   })

通过electron自定义弹框来限制是否退出
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容