作者:Kurosaki

本节旨在汇总在开发Electron 窗口可能遇到的问题,做一个汇总,后续遇到问题会持续更新。

1. 窗口闪烁问题。

  1. const { BrowserWindow } = require('electron');
  2. const win = new BrowserWindow();
  3. win.loadURL('https://github.com');

使用new BrowserWindow() 创建出窗口,如果不作任何配置的话,窗口就会出现,默认是白色的;这个时候使用win.loadURL(‘https://github.com'),加载远程资源,窗口重新渲染,从而导致窗口出现闪烁。

解决方法:

  1. const { BrowserWindow } = require('electron');
  2. const win = new BrowserWindow({ show:false });
  3. win.loadURL('https://github.com');
  4. win.once('ready-to-show',()=>{
  5. win.show();
  6. })

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 关机会把所有的窗口关闭,如果存在

  1. // 窗口注册close事件
  2. win.on('close',(event)=>{
  3. event.preventDefault() // 阻止窗口关闭
  4. })

这种代码,会导致阻止系统关机。

4. Window 系统下,使用 hide() 方法,可能导致页面挂住不能用。

导致这种场景可以是因为调用 hide() 之后不调用 show() 方法,而只是调用 restore() 方法,会导致页面挂住不能用。所以得在 restore() 方法之后添加 show() 方法

5. 新版Electron,导致渲染进程无法访问到remote模块。

切换成新版的Electron,new BrowserWindow(options)配置更新,webPreferences中配置enableRemoteModule:true

6. macOS下无边框窗口,顶部拖拽问题。

在创建窗口时,配置一下preload.js,代码如下:

  1. function initTopDrag() {
  2. const topDiv = document.createElement('div') // 创建节点
  3. topDiv.style.position = 'fixed' // 一直在顶部
  4. topDiv.style.top = '0'
  5. topDiv.style.left = '0'
  6. topDiv.style.height = '20px' // 顶部20px才可拖动
  7. topDiv.style.width = '100%' // 宽度100%
  8. topDiv.style.zIndex = '9999' // 悬浮于最外层
  9. topDiv.style.pointerEvents = 'none' // 用于点击穿透
  10. topDiv.style['-webkit-user-select'] = 'none' // 禁止选择文字
  11. topDiv.style['-webkit-app-region'] = 'drag' // 拖动
  12. document.body.appendChild(topDiv) // 添加节点
  13. }
  14. window.addEventListener('DOMContentLoaded', function onDOMContentLoaded() {
  15. initTopDrag()
  16. })

7. Window系统下,隐藏菜单问题。

Window系统下,菜单长的很丑,有2种方案可以隐藏菜单

  1. 使用无边框窗口,去除菜单和边框,自己手写一个控制的边框,目前github都有这些库;
  2. 使用autoHideMenuBar:true 但是按下ALT键会出现菜单

    8. 窗口之间通信。

  3. 主进程创建窗口

配置preload.js,将通信方法挂载到window

  1. /**
  2. * 这个是用于窗口通信例子的preload,
  3. * preload执行顺序在窗口js执行顺序之前
  4. */
  5. import { ipcRenderer, remote } from 'electron'
  6. const { argv } = require('yargs')
  7. const { BrowserWindow } = remote
  8. // 父窗口监听子窗口事件
  9. ipcRenderer.on('communication-to-parent', (event, msg) => {
  10. alert(msg)
  11. })
  12. const { parentWindowId } = argv
  13. if (parentWindowId !== 'undefined') {
  14. const parentWindow = BrowserWindow.fromId(parentWindowId as number)
  15. // 挂载到window
  16. // @ts-ignore
  17. window.send = (params: any) => {
  18. parentWindow.webContents.send('communication-to-parent', params)
  19. }
  20. }

创建窗口传入id

  1. browserWindow.webContents.on('new-window', (event, url, frameName, disposition) => {
  2. event.preventDefault()
  3. // 在通过BrowserWindow创建窗口
  4. const win = new BrowserWindow({
  5. show:false,
  6. webPreferences: {
  7. preload:preload.js,
  8. additionalArguments:[`--parentWindow=${browserWindow.id}`] // 把父窗口的id传过去
  9. }
  10. });
  11. win.loadURl(url);
  12. win.once('ready-to-show',()=>{
  13. win.show()
  14. })
  15. })
  1. 父子窗口

    没有上述那么麻烦,配置preload就可以,具体实现

  1. import { remote, ipcRenderer } from 'electron'
  2. // 父窗口监听子窗口事件
  3. ipcRenderer.on('communication-to-parent', (event, msg) => {
  4. alert(msg)
  5. })
  6. const parentWindow = remote.getCurrentWindow().getParentWindow()
  7. // @ts-ignore
  8. window.sendToParent = (params: any) =>
  9. parentWindow.webContents.send('communication-to-parent', params)
  1. 渲染进程创建窗口

    渲染进程通信很简单,通过window.open,window.open会返回一个windowObjectReference 通过postMessage就可以通信了。并且window.open 支持传preload等配置。

    9. 窗口全屏问题。

    使用按钮全屏和退出全屏是可以的,但是先点击左上角🚥全屏,再使用按钮退出全屏,是不行的。因为无法知道当前的状态是全屏,还是不是全屏。

配置preload,使用Electron自带的全屏API

  1. import { remote } from 'electron'
  2. const setFullScreen = remote.getCurrentWindow().setFullScreen
  3. const isFullScreen = remote.getCurrentWindow().isFullScreen
  4. window.setFullScreen = setFullScreen
  5. window.isFullScreen = isFullScreen

10. macOS 开发环境,可能存在文件读取权限问题。

在macOS下,我们启动Electron应用,是在Application文件夹的外面,运行在一个只读的disk image。基于安全的原因,需要存在用户自己授权,electron-util做了一个很好的封装。可以使用 electron-util 中的 enforceMacOSAppLocation 方法。该文档electron-util

  1. const { app, BrowserWindow } = require('electron')
  2. const { enforceMacOSAppLocation } = require('electron-util')
  3. function createWindow() {
  4. enforceMacOSAppLocation()
  5. const mainWindow = new BrowserWindow({
  6. width: 800,
  7. height: 600,
  8. webPreferences: {
  9. nodeIntegration: true,
  10. },
  11. })
  12. mainWindow.loadFile('index.html')
  13. }
  14. app.on('ready', createWindow)
  15. app.on('window-all-closed', function () {
  16. if (process.platform !== 'darwin') {
  17. app.quit()
  18. }
  19. })
  20. app.on('activate', function () {
  21. if (BrowserWindow.getAllWindows().length === 0) {
  22. createWindow()
  23. }
  24. })

enforceMacOSAppLocation 方法封装

  1. 'use strict';
  2. const api = require('./api');
  3. const is = require('./is');
  4. module.exports = () => {
  5. if (is.development || !is.macos) {
  6. return;
  7. }
  8. if (api.app.isInApplicationsFolder()) {
  9. return;
  10. }
  11. const appName = 'name' in api.app ? api.app.name : api.app.getName();
  12. const clickedButtonIndex = api.dialog.showMessageBoxSync({
  13. type: 'error',
  14. message: 'Move to Applications folder?',
  15. detail: `${appName} must live in the Applications folder to be able to run correctly.`,
  16. buttons: [
  17. 'Move to Applications folder',
  18. `Quit ${appName}`
  19. ],
  20. defaultId: 0,
  21. cancelId: 1
  22. });
  23. if (clickedButtonIndex === 1) {
  24. api.app.quit();
  25. return;
  26. }
  27. api.app.moveToApplicationsFolder({
  28. conflictHandler: conflict => {
  29. if (conflict === 'existsAndRunning') { // Can't replace the active version of the app
  30. api.dialog.showMessageBoxSync({
  31. type: 'error',
  32. message: `Another version of ${api.app.getName()} is currently running. Quit it, then launch this version of the app again.`,
  33. buttons: [
  34. 'OK'
  35. ]
  36. });
  37. api.app.quit();
  38. }
  39. return true;
  40. }
  41. });
  42. };

如果你遇到Electron相关的问题,可以评论一下,我们共同解决,一起成长。