在Electron中有2中方式进行通信:
1、ipcRenderer:渲染页面向主进程发送消息。
2、ipcMain:监听消息对象并接收
3、BrowserWindow:主进程窗口对象向渲染进程发送消息。
ipcRenderer:渲染进程(Vue.js)
<template>
<div>
<h1>
Hello Henry
</h1>
<button @click="sendMainMsg">send</button>
</div>
</template>
<script>
const ipcRenderer = window.require('electron').ipcRenderer;
export default{
name:"home",
data(){
return{
}
},
mounted(){
//接收主进程发送的消息。
ipcRenderer.on('hello_child', function(event, data) {
console.log(data)
})
},
methods:{
sendMainMsg(){
//主动向主进程发送消息
var ret_msg = ipcRenderer.sendSync('windows', JSON.stringify({
command: "child_call_parent"
}));
console.log("主程序返回消息:"+ret_msg)
}
},
components:{}
}
</script>
<style>
</style>
ipcMain:主进程监听消息对象并接收
'use strict'
import { app, protocol, BrowserWindow, ipcMain } from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
let win
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
const path = require("path");
async function createWindow() {
console.log(process.env.ELECTRON_NODE_INTEGRATION)
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
nodeIntegrationInSubFrames: true
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
app.on('ready', async () => {
createWindow()
setTimeout(()=>{
//直接使用windows窗口对象向渲染进程发送消息,使用延时是因为主进程加载完成 渲染进程还未加载
win.webContents.send("hello_child", "哈喽子级!");
}, 3000)
ipcMain.on("windows", function(event, data) {
switch (JSON.parse(data).command) {
case "child_call_parent":
event.returnValue = "OK";
break;
}
})
})