内置窗口插件
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
const Addon = require('ee-core/addon');
/**
* 打开新窗口
*/
createWindow (args) {
const { type, content, windowName, windowTitle } = args;
let contentUrl = null;
if (type == 'html') {
contentUrl = path.join('file://', electronApp.getAppPath(), content)
} else if (type == 'web') {
contentUrl = content;
} else if (type == 'vue') {
let addr = 'http://localhost:8080'
if (Ps.isProd()) {
const mainServer = Conf.getValue('mainServer');
if (Conf.isFileProtocol(mainServer)) {
addr = mainServer.protocol + path.join(Ps.getHomeDir(), mainServer.indexPath);
} else {
addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
}
}
contentUrl = addr + content;
} else {
// some
}
console.log('contentUrl: ', contentUrl);
let opt = {
title: windowTitle
}
const win = Addon.get('window').create(windowName, opt);
const winContentsId = win.webContents.id;
// load page
win.loadURL(contentUrl);
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/02/08, 11:20:40