作者: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种计划能够暗藏菜单
  1. 应用无边框窗口,去除菜单和边框,本人手写一个管制的边框,目前github都有这些库;
  2. 应用autoHideMenuBar:true 然而按下ALT键会呈现菜单

8. 窗口之间通信。

  1. 主过程创立窗口

配置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-ignore  window.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()    })})
  1. 父子窗口
没有上述那么麻烦,配置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)
  1. 渲染过程创立窗口
渲染过程通信很简略,通过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 app                api.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相干的问题,能够评论一下,咱们独特解决,一起成长。


对 Electron 感兴趣?请关注咱们的开源我的项目 Electron Playground,带你极速上手 Electron。

咱们每周五会精选一些有意思的文章和音讯和大家分享,来掘金关注咱们的 晓前端周刊。


咱们是好将来 · 晓黑板前端技术团队。
咱们会常常与大家分享最新最酷的行业技术常识。
欢送来 知乎、掘金、Segmentfault、CSDN、简书、开源中国、博客园 关注咱们。