2

https://file.zzc.icu/knowledge/27328964206592.jpg

主线程:Main

渲染线程:Renderer

Main --> Renderer

https://electronjs.org/docs/api/web-contents

Main

const {app, BrowserWindow} = require('electron')
let win = null

app.on('ready', () => {
  win = new BrowserWindow({width: 800, height: 600})
  win.loadURL(`file://${__dirname}/index.html`)
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('ping', 'whoooooooh!')
  })
})

Renderer

<html>
<body>
  <script>
    require('electron').ipcRenderer.on('ping', (event, message) => {
      console.log(message)  // Prints 'whoooooooh!'
    })
  </script>
</body>
</html>

Renderer --> Main

https://electronjs.org/docs/api/ipc-main

Renderer

// synchronous
const {ipcRenderer} = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"

// asynchronous
ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log(arg) // prints "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')

Main

// synchronous
ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg)  // prints "ping"
  event.returnValue = 'pong'
})

// asynchronous
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg)  // prints "ping"
  event.sender.send('asynchronous-reply', 'pong')
})

Global Object

Main

// Define
global.sharedObject = {
  someProperty: 'default value'
}

// Get
var a = global.sharedObject.someProperty

// Set
global.sharedObject = 'custom value'

Renderer

const electron = require('electron')

// Get
var a = electron.remote.getGlobal('sharedObject').someProperty

// Set
electron.remote.getGlobal('sharedObject').someProperty = 'new value'

Sulfonamide
397 声望12 粉丝

技能树点亮中。