使用 Electron 处理窗体崩溃和挂起

使用 Electron 处理窗体崩溃和挂起

此系列文章的应用示例已发布于 GitHub: electron-api-demos-Zh_CN. 能够 Clone 或下载后运行查看. 欢迎 Star .html

BrowserWindow 模块将在渲染器进程崩溃或挂起时发出事件. 您能够监听这些事件, 并给用户从新加载, 等待或关闭该窗口的机会.git

在浏览器中打开 完整的 API 文档 .github

进程崩溃后重载窗体

支持: Win, macOS, Linux | 进程: Mainweb

在这个示例中咱们建立一个新窗口 (经过 remote 模块) 并提供了一个使用 process.crash() 方法强制崩溃的连接.windows

当前窗体正在监听崩溃事件, 当此事件发生时, 它提供用户两个选项: 从新加载或关闭.api

渲染器进程浏览器

const BrowserWindow = require('electron').remote.BrowserWindow
const dialog = require('electron').remote.dialog

const path = require('path')

const processCrashBtn = document.getElementById('process-crash')

processCrashBtn.addEventListener('click', function (event) {
  const crashWinPath = path.join('file://', __dirname, '../../sections/windows/process-crash.html')
  let win = new BrowserWindow({ width: 400, height: 320 })

  win.webContents.on('crashed', function () {
    const options = {
      type: 'info',
      title: '渲染器进程崩溃',
      message: '这个进程已经崩溃.',
      buttons: ['重载', '关闭']
    }
    dialog.showMessageBox(options, function (index) {
      if (index === 0) win.reload()
      else win.close()
    })
  })

  win.on('close', function () { win = null })
  win.loadURL(crashWinPath)
  win.show()
})

进程挂起后重载窗体

支持: Win, macOS, Linux | 进程: Mainelectron

在这个示例中咱们建立一个新窗口 (经过 remote 模块) 并提供了一个使用 process.hang() 方法强制挂起进程的连接.ui

当前窗体正在监听进程是否真正无响应 (这可能须要长达30秒). 当此事件发生时, 它提供用户两个选项: 从新加载或关闭.spa

渲染器进程

const BrowserWindow = require('electron').remote.BrowserWindow
const dialog = require('electron').remote.dialog

const path = require('path')

const processHangBtn = document.getElementById('process-hang')

processHangBtn.addEventListener('click', function (event) {
  const hangWinPath = path.join('file://', __dirname, '../../sections/windows/process-hang.html')
  let win = new BrowserWindow({ width: 400, height: 320 })

  win.on('unresponsive', function () {
    const options = {
      type: 'info',
      title: '渲染器进程挂起',
      message: '这个进程已经被挂起.',
      buttons: ['重载', '关闭']
    }
    dialog.showMessageBox(options, function (index) {
      if (index === 0) win.reload()
      else win.close()
    })
  })

  win.on('close', function () { win = null })
  win.loadURL(hangWinPath)
  win.show()
})

高级技巧

等待进程再次响应.

在进程挂起的的状况下, 第三个选择是等待并查看问题是否解决, 容许进程再次响应. 为此, 请使用 BrowserWindow 的 "responsive" 事件, 以下所示:

win.on('responsive', function () {
  // 当窗口再次响应时作些什么
})

若是这边文章对您有帮助, 感谢 下方点赞 或 Star GitHub: electron-api-demos-Zh_CN 支持, 谢谢.

相关文章
相关标签/搜索