在 webview 应用程序中处理电子应用程序的 onclose 事件

分享于2023年02月08日 electron electron-builder javascript reactjs webview 问答
【问题标题】:handling the onclose event of electron app inside the webview app在 webview 应用程序中处理电子应用程序的 onclose 事件
【发布时间】:2022-12-20 07:18:12
【问题描述】:

我有一个电子应用程序,其中的 Ui 是使用 React js 构建的。在 react js ui 中,其他网络应用程序是使用 webview 加载的。

我的问题是当电子应用程序关闭时我需要保存 webview 应用程序的数据。

我想知道如何在 webview 应用程序中访问电子应用程序的 onClose 事件。


【解决方案1】:

刚刚遇到类似的东西。你可以做这样的事情。

在主进程中:

const { ipcMain, app, webContents } = require('electron')

app.on('will-quit', event => {
    event.preventDefault()

    let readyCount = 0
    ipcMain.on('ready-to-quit', () => {
        readyCount++
        if (readyCount === allWebContents.length) {
            app.exit()
        }
    })

    const allWebContents = webContents.getAllWebContents()
    allWebContents.forEach(contents => contents.send('app-will-quit'))
})

在Renderer进程中:

const { ipcRenderer } = require('electron')

ipcRenderer.once('app-will-quit', () => {
    // do stuff
    ipcRenderer.send('ready-to-quit')
})

【讨论】: