内置窗口插件
ee-core: v1.4.0
ee-core: v2.0.3 版后,尽量使用模块化api,减少对this.app依赖
# 说明
用来创建多窗口,并实现 窗口/主进程、窗口/子窗口 之间互相通信。
# 配置
# electron/config/config.default.js
/**
* 插件功能
*/
config.addons = {
window: {
enable: true,
},
}
# 代码
# ee-core/addon/window/index.js
# 使用
主进程
# electron/controller/example.js
/**
* 打开新窗口
*/
createWindow (args) {
let content = null;
if (args.type == 'html') {
content = path.join('file://', electronApp.getAppPath(), args.content)
} else if (args.type == 'web') {
content = args.content;
} else if (args.type == 'vue') {
let addr = 'http://localhost:8080'
if (this.config.env == 'prod') {
const mainServer = this.app.config.mainServer;
addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
}
content = addr + args.content;
} else {
// some
}
# 调用窗口插件
const addonWindow = this.app.addon.window;
let opt = {
title: args.windowName || 'new window'
}
const name = args.windowName || 'window-1';
const win = addonWindow.create(name, opt);
const winContentsId = win.webContents.id;
// load page
win.loadURL(content);
return winContentsId
}
# electron/controller/example.js
/**
* 获取窗口contents id
*/
getWCid (args) {
const addonWindow = this.app.addon.window;
// 主窗口的name默认是main,其它窗口name开发者自己定义
const name = args;
const id = addonWindow.getWCid(name);
return id;
}
前端
# frontend/src/views/base/socket/Ipc.vue
/**
* 监听通信频道
*/
init () {
const self = this;
// 监听 窗口2 发来的消息
this.$ipc.removeAllListeners(specialIpcRoute.window2ToWindow1);
this.$ipc.on(specialIpcRoute.window2ToWindow1, (event, arg) => {
this.$message.info(arg);
})
},
/**
* 创建窗口
*/
createWindow (index) {
this.$ipcInvoke(ipcApiRoute.createWindow, this.views[index]).then(id => {
console.log('[createWindow] id:', id);
})
},
/**
* 向新窗口发消息
*/
async sendTosubWindow () {
// 新窗口id
this.newWcId = await this.$ipcInvoke(ipcApiRoute.getWCid, this.windowName);
this.$ipc.sendTo(this.newWcId, specialIpcRoute.window1ToWindow2, '窗口1通过 sendTo 给窗口2发送消息');
},
# frontend/src/views/base/subwindow/Ipc.vue
/**
* 监听通信频道
*/
init () {
const self = this;
// 监听主窗口发来的消息
this.$ipc.removeAllListeners(specialIpcRoute.window1ToWindow2);
this.$ipc.on(specialIpcRoute.window1ToWindow2, (event, arg) => {
this.$message.info(arg);
})
},
/**
* 向主窗口发消息
*/
sendTosubWindow () {
// 获取主窗口id
this.$ipcInvoke(ipcApiRoute.getWCid, 'main').then(id => {
this.mainWCid = id;
this.$ipc.sendTo(this.mainWCid, specialIpcRoute.window2ToWindow1, '窗口2 通过 sendTo 给主窗口发送消息');
});
},
上次更新: 2025/04/10, 03:07:49