electron基础篇通信

25次阅读

共计 1542 个字符,预计需要花费 4 分钟才能阅读完成。

主进程与渲染进程之间的通信

(异步) 渲染进程给主进程发送消息,主进程监听到后,给渲染进程反馈

渲染进程

//ipcRenderer.js

// 渲染进程给主进程发送消息
var sendreplay = document.querySelector('#sendreplay')
sendreplay.onclick = function() {ipcRenderer.send('sendreplay', 'this is renderer aaa')
}
// 接收主进程的反馈
ipcRenderer.on('replay', function(event, data) {console.log(data)
})

主进程

//ipcMain.js

// 监听渲染进程发送过来的消息
ipcMain.on('sendreplay', function(event, data) {console.log(data)
  // 反馈给渲染进程
  event.sender.send('replay', 'ok haha')
})

(同步)

渲染进程

sendsync.onclick = function() {var msg = ipcRenderer.sendSync('sendresync', 'this is renderer ccc')
  console.log('bb' + msg)
}

主进程

ipcMain.on('sendresync', function(event, data) {console.log('aa' + data)
  event.returnValue = 'this is sync main'
})

渲染进程没有办法直接调用主进程中的模块,通过 remote 模块间接的调用主进程中的模块

渲染进程之间的通信

localStorage

a 渲染进程先给主进程发送消息,主进程再通知 b 渲染进程,b 进程再通知 a 进程

a 渲染进程

// 发送
var openNewWindow = document.querySelector('#openNewWindow')
openNewWindow.onclick = function() {
  var aid = 123
  ipcRenderer.send('openNewWindow', aid)
}

// 监听
ipcRenderer.on('toIndex', function(event, data) {console.log(data)
})

主进程

ipcMain.on('openNewWindow', function(event, aid) {
  //1. 获取当前窗口的对象
  var winId = BrowserWindow.getFocusedWindow().id
  // 调用 BrowserWindow 打开新窗口
  win = new BrowserWindow({
    width: 400,
    height: 300
    // frame:false,
    // fullscreen:true
  })
  win.loadURL(path.join('file:', __dirname, '../news.html'))

  win.webContents.openDevTools()

  win.webContents.on('did-finish-load', function() {win.webContents.send('toNews', aid, winId)
  })

  win.on('closed', () => {win = null})
})

b 渲染进程

ipcRenderer.on('toNews', function(event, aid, winId) {console.log(aid)
  // 发送
  var firstWin = BrowserWindow.fromId(winId)
  firstWin.webContents.send('toIndex', 'this is news')
})

正文完
 0