electron如何与web对接
mian.js
//创建主窗体 function createWindow(options) { // Create the browser window. mainWindow = new BrowserWindow({ modal: true, fullscreen: false, autoHideMenuBar: true, titleBarStyle: "hidden", skipTaskbar: true, webPreferences: { // webSecurity: false, // allowRunningInsecureContent: true, nodeIntegration: true, contextIsolation: true, preload: path.join(__dirname, 'preload.js') }, show: false }) mainWindow.loadURL(url); } app.whenReady().then(() => { //防止程序多开 const gotTheLock = app.requestSingleInstanceLock() if (!gotTheLock) { dialog.showMessageBoxSync({ message: "程序已经在运行", type: "warning", title: "提示" }); app.quit() } registryShortcut(); //注册快捷键 registryTray(); //注册系统托盘 createMiniSizeWindow(); //创建最小化窗体 createLodingWindow(); //创建加载窗体(包含自动更新) if (NODE_ENV === "development") { //createLoginWindow(); createWindow(); } app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createLoginWindow() }) }) // 加载主窗体 ipcMain.on('loadMainWindow', function (res, args) { createWindow(args); })
preload.js
const electron = require('electron') const { ipcRenderer, contextBridge } = require('electron') window.addEventListener('DOMContentLoaded', () => { //加载完成检查更新 ipcRenderer.send("checkForUpdate"); }) //桥接网页内容 contextBridge.exposeInMainWorld('winApi', { //关闭窗口 closeWindow: () => { ipcRenderer.send('handelClose') }, //最小化窗口 minimizeWindow: () => { ipcRenderer.send('handelMiniWindow') }, //程序更新信息 updateMessage: (callback) => ipcRenderer.on("updateMessage", callback), //下载进度 downloadProgress: (callback) => ipcRenderer.on("downloadProgress", callback), //立即更新 isUpdateNow: () => ipcRenderer.on("isUpdateNow", () => { ipcRenderer.send("isUpdateNow"); }), //加载主窗体 loadMainWindow: (options) => { ipcRenderer.send("loadMainWindow", options) }, //显示主窗体 showMainWindow: () => { ipcRenderer.send("showMainWindow") } });
electron跟web端进程通信,主要是依靠桥接器,如上所示
electron加载以后会将winApi加入到js的window对象中,前端可以通过调用window对象上的winodw.winApi.minimizeWindow()方法,最小化主窗体等。