主线程: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'
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。