方法1:在两个网页(渲染进程)间共享数据最简单的方法是使用浏览器中已经实现的 HTML5 API。 其中比较好的方案是用 Storage API, localStorage
,sessionStorage
或者 IndexedDB。web
方法2:使用Electron
内的 IPC 机制实现。将数据存储在主进程的某个全局变量中,而后在多个渲染进程中使用 remote
模块来访问它。例:浏览器
//主进程中session
Global.saveData = { shareData: data};electron
//在窗口1设置修改数据ui
require('electron').remote.getGlobal(‘saveData’). shareData = ‘new value’code
//在窗口2中得到更新的数据接口
require('electron').remote.getGlobal(‘saveData’). shareData进程
方法3:主进程作消息中转事件
//在主进程中监听窗口1发送事件,并接受数据后发送给窗口2ip
ipcMain.on('ping-event', (event, arg) => {
yourWindow.webContents.send('pong-event', 'something');
}
//在渲染进程中,窗口1发送数据
ipcRenderer.send('ping-event', (event, arg) => {
// do something
})
//在渲染进程的窗口2中监听主进程发送的事件,接收数据
ipcRenderer.on('pong-event', (event, arg) => {
// do something })
方法4:利用 remote 接口直接获取渲染进程发送消息:
主要步骤:
·1.在窗口1中获取当前窗口的id,窗口加载完成后发送一个事件,携带当前窗口id和发送的数据; 而后监听窗口2返回的数据
constwindowID = BrowserWindow.getFocusedWindow().id;
'share-data'win.webContents.send(,data, windowID);
'factorial-computed'function (event, data, id) ipcRenderer.on(,{
//此处的data就是窗口2传输来的数据
})
2. 在窗口2中监听窗口1事件
const ipc = require('electron').ipcRenderer
const BrowserWindow = require('electron').remote.BrowserWindow
ipc.on(' share-data', function (event,data,fromWindowId) {
//此处的data就是窗口1传输来的数据
const fromWindow = BrowserWindow.fromId(fromWindowId)
fromWindow.webContents.send('factorial-computed',data, fromWindowId)
window.close()
})
//在渲染器进程中
constrequire'electron'ipc =().ipcRenderer
constdocument'sync-msg'syncMsgBtn =.getElementById()
'click'function () syncMsgBtn.addEventListener(,{
const'synchronous-message''ping' reply = ipc.sendSync(,)
const`同步消息回复: ${reply}` message =
document'sync-reply' .getElementById().innerHTML = message
})
//在主进程中
constrequire'electron'ipc =().ipcMain
'synchronous-message'function (event, arg) ipc.on(,{
'pong' event.returnValue =
})