【Electron Playground】Electron 窗口问题汇总

作者: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 } = argv
if (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-ignore
window.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().setFullScreen
const isFullScreen = remote.getCurrentWindow().isFullScreen

window.setFullScreen = setFullScreen
window.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。

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


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

posted @ 2020-12-16 10:19  晓前端  阅读(2401)  评论(1编辑  收藏  举报