@truenewx/tnxet
Version:
互联网技术解决方案:Electron扩展支持
67 lines (58 loc) • 2.39 kB
text/typescript
/**
* 对Electron主进程的扩展支持
*/
import {app, BrowserWindow, BrowserWindowConstructorOptions, ipcMain} from 'electron';
import constants from './constants.ts';
import * as MainFileUtil from './main/util/file.ts';
import ipcListeners from './main/ipc-listener/index.ts';
function registerIpcListeners() {
const eventNames = new Set<string>();
ipcListeners.forEach(listener => {
let eventName = listener.name;
if (eventName && typeof listener.listen === 'function') {
if (eventNames.has(eventName.request)) {
console.error(`Duplicated main ipc listener: ${eventName.request}`);
app.exit(1);
return;
}
ipcMain.on(eventName.request, (event, requestId, ...args) => {
listener.listen(...args).then((result: any) => {
event.reply(eventName.response, requestId, null, result);
}).catch(error => {
event.reply(eventName.response, requestId, error);
});
});
eventNames.add(eventName.request);
}
});
}
export default class TnxetMain {
isProduction() {
return !process.argv[0].endsWith('electron.exe');
}
getAbsolutePathBasedOnApp(filePath: string): string {
return MainFileUtil.getAbsolutePathBasedOnApp(filePath);
}
createWindow(options?: BrowserWindowConstructorOptions): BrowserWindow {
let win = new BrowserWindow(options);
registerIpcListeners();
win.webContents.on('before-input-event', (event, input) => {
if (input.key === 'F5') {
event.preventDefault(); // 阻止默认行为
win.webContents.reload(); // 刷新页面
}
});
return win;
}
enableDevTools(win: BrowserWindow, inputKey = 'F12') {
win.webContents.on('before-input-event', (event, input) => {
if (input.key === inputKey) {
event.preventDefault(); // 阻止默认行为
win.webContents.toggleDevTools(); // 打开或关闭开发者工具
}
});
}
sendCommand(win: BrowserWindow, name: string, ...args: any[]) {
win.webContents.send(constants.channel.command, {name, args});
}
}