作者:Kurosaki
本节旨在汇总在开发Electron 窗口可能遇到的问题,做一个汇总,后续遇到问题会持续更新。
1. 窗口闪烁问题。
const { BrowserWindow } = require('electron');const win = new BrowserWindow();win.loadURL('https://github.com');
使用new BrowserWindow() 创建出窗口,如果不作任何配置的话,窗口就会出现,默认是白色的;这个时候使用win.loadURL(‘https://github.com'),加载远程资源,窗口重新渲染,从而导致窗口出现闪烁。
解决方法:
const { BrowserWindow } = require('electron');const win = new BrowserWindow({ show:false });win.loadURL('https://github.com');win.once('ready-to-show',()=>{win.show();})
2. 老版Window7系统下,窗口白屏问题。
公司业务开发的Electron应用,是给老师用的,有些老师是那种老版本Window7,并且关闭了自动更新。
解决办法:
安装最新版的.NET Framework
官方下载地址:https://dotnet.microsoft.com/download/dotnet-framework
相关issue: https://github.com/electron/electron/issues/25186
3. macOS下电脑关机,Electron应用阻止关机问题。
macOS 关机会把所有的窗口关闭,如果存在
// 窗口注册close事件win.on('close',(event)=>{event.preventDefault() // 阻止窗口关闭})
4. Window 系统下,使用 hide() 方法,可能导致页面挂住不能用。
导致这种场景可以是因为调用 hide() 之后不调用 show() 方法,而只是调用 restore() 方法,会导致页面挂住不能用。所以得在 restore() 方法之后添加 show() 方法
5. 新版Electron,导致渲染进程无法访问到remote模块。
切换成新版的Electron,new BrowserWindow(options)配置更新,webPreferences中配置enableRemoteModule:true
6. macOS下无边框窗口,顶部拖拽问题。
在创建窗口时,配置一下preload.js,代码如下:
function initTopDrag() {const topDiv = document.createElement('div') // 创建节点topDiv.style.position = 'fixed' // 一直在顶部topDiv.style.top = '0'topDiv.style.left = '0'topDiv.style.height = '20px' // 顶部20px才可拖动topDiv.style.width = '100%' // 宽度100%topDiv.style.zIndex = '9999' // 悬浮于最外层topDiv.style.pointerEvents = 'none' // 用于点击穿透topDiv.style['-webkit-user-select'] = 'none' // 禁止选择文字topDiv.style['-webkit-app-region'] = 'drag' // 拖动document.body.appendChild(topDiv) // 添加节点}window.addEventListener('DOMContentLoaded', function onDOMContentLoaded() {initTopDrag()})
7. Window系统下,隐藏菜单问题。
Window系统下,菜单长的很丑,有2种方案可以隐藏菜单
配置preload.js,将通信方法挂载到window
/*** 这个是用于窗口通信例子的preload,* preload执行顺序在窗口js执行顺序之前*/import { ipcRenderer, remote } from 'electron'const { argv } = require('yargs')const { BrowserWindow } = remote// 父窗口监听子窗口事件ipcRenderer.on('communication-to-parent', (event, msg) => {alert(msg)})const { parentWindowId } = argvif (parentWindowId !== 'undefined') {const parentWindow = BrowserWindow.fromId(parentWindowId as number)// 挂载到window// @ts-ignorewindow.send = (params: any) => {parentWindow.webContents.send('communication-to-parent', params)}}
创建窗口传入id
browserWindow.webContents.on('new-window', (event, url, frameName, disposition) => {event.preventDefault()// 在通过BrowserWindow创建窗口const win = new BrowserWindow({show:false,webPreferences: {preload:preload.js,additionalArguments:[`--parentWindow=${browserWindow.id}`] // 把父窗口的id传过去}});win.loadURl(url);win.once('ready-to-show',()=>{win.show()})})
- 父子窗口
没有上述那么麻烦,配置preload就可以,具体实现
import { remote, ipcRenderer } from 'electron'// 父窗口监听子窗口事件ipcRenderer.on('communication-to-parent', (event, msg) => {alert(msg)})const parentWindow = remote.getCurrentWindow().getParentWindow()// @ts-ignorewindow.sendToParent = (params: any) =>parentWindow.webContents.send('communication-to-parent', params)
- 渲染进程创建窗口
渲染进程通信很简单,通过window.open,window.open会返回一个
windowObjectReference通过postMessage就可以通信了。并且window.open 支持传preload等配置。9. 窗口全屏问题。
使用按钮全屏和退出全屏是可以的,但是先点击左上角🚥全屏,再使用按钮退出全屏,是不行的。因为无法知道当前的状态是全屏,还是不是全屏。
配置preload,使用Electron自带的全屏API
import { remote } from 'electron'const setFullScreen = remote.getCurrentWindow().setFullScreenconst isFullScreen = remote.getCurrentWindow().isFullScreenwindow.setFullScreen = setFullScreenwindow.isFullScreen = isFullScreen
10. macOS 开发环境,可能存在文件读取权限问题。
在macOS下,我们启动Electron应用,是在Application文件夹的外面,运行在一个只读的disk image。基于安全的原因,需要存在用户自己授权,electron-util做了一个很好的封装。可以使用 electron-util 中的 enforceMacOSAppLocation 方法。该文档electron-util。
const { app, BrowserWindow } = require('electron')const { enforceMacOSAppLocation } = require('electron-util')function createWindow() {enforceMacOSAppLocation()const mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {nodeIntegration: true,},})mainWindow.loadFile('index.html')}app.on('ready', createWindow)app.on('window-all-closed', function () {if (process.platform !== 'darwin') {app.quit()}})app.on('activate', function () {if (BrowserWindow.getAllWindows().length === 0) {createWindow()}})
enforceMacOSAppLocation 方法封装
'use strict';const api = require('./api');const is = require('./is');module.exports = () => {if (is.development || !is.macos) {return;}if (api.app.isInApplicationsFolder()) {return;}const appName = 'name' in api.app ? api.app.name : api.app.getName();const clickedButtonIndex = api.dialog.showMessageBoxSync({type: 'error',message: 'Move to Applications folder?',detail: `${appName} must live in the Applications folder to be able to run correctly.`,buttons: ['Move to Applications folder',`Quit ${appName}`],defaultId: 0,cancelId: 1});if (clickedButtonIndex === 1) {api.app.quit();return;}api.app.moveToApplicationsFolder({conflictHandler: conflict => {if (conflict === 'existsAndRunning') { // Can't replace the active version of the appapi.dialog.showMessageBoxSync({type: 'error',message: `Another version of ${api.app.getName()} is currently running. Quit it, then launch this version of the app again.`,buttons: ['OK']});api.app.quit();}return true;}});};
如果你遇到Electron相关的问题,可以评论一下,我们共同解决,一起成长。
