Electron消息通信 (主进程与渲染进程通信)

在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;
		}
	})
})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值