[electron playground] summary of electron window problems



The purpose of this section is to summarize the problems that may be encountered in the development of the electron window, and make a summary, which will be updated continuously in the future.

1. The window flickers.

const { BrowserWindow } = require('electron');
const win = new BrowserWindow();

Use new browserwindow() to create a window. If no configuration is made, the window will appear. The default is white; Use win. Loadurl (‘https://github.com‘, load the remote resource, and render the window again, causing the window to flicker.


const { BrowserWindow } = require('electron');
const win = new BrowserWindow({ show:false });


2. The old version of window7 system, the window white screen problem.

The electron application developed by the company’s business is for teachers. Some teachers are the old version of window7 and turn off automatic update.

terms of settlement:
Install the latest version of. Net framework
Official download address:https://dotnet.microsoft.com/download/dotnet-framework
Related issues:https://github.com/electron/electron/issues/25186

3. MacOS computer shutdown, electron application to prevent shutdown.

MacOS shutdown will close all windows, if any

//Window registration close event
  Event. Preventdefault() // prevent windows from closing

This kind of code will cause to prevent the system from shutting down.

4. Window  Under the system, usinghide()  Method, which may cause the page to hang.

This scenario can be caused by callinghide()  Do not call aftershow()  Method, instead of just callingrestore()  Method will cause the page to hang and cannot be used. So it’s up to yourestore()  Methodshow()  method

5. Due to the new version of electron, the rendering process cannot access the remote module.

Switch to the new version of electron, new browserwindow (options) configuration update, and configure enable remote in webpreferences odule:true

6. The problem of borderless window and top drag in MacOS.

When creating a window, configure preload.js. The code is as follows:

function initTopDrag() {
  Const topdiv = document. CreateElement ('div ') // create node
  Topdiv. Style. Position ='fixed '// always at the top
  topDiv.style.top = '0'
  topDiv.style.left = '0'
  Topdiv. Style. Height ='20px '// the top 20px can be dragged
  Topdiv. Style. Width ='100% '// width 100%
  Topdiv.style.zindex ='9999 '// suspended in the outermost layer
  Topdiv. Style. Pointerevents ='none '// used for click through
  Topdiv. Style ['- WebKit user select'] ='none '// text selection prohibited
  Topdiv. Style ['- WebKit app region'] ='drag '// drag
  Document. Body. AppendChild (topdiv) // add node

window.addEventListener('DOMContentLoaded', function onDOMContentLoaded() {

7. Hidden menu in window system.

Under the window system, the menu is very ugly. There are two ways to hide the menu

  1. Use borderless windows, remove menus and borders, and write a controlled border by yourself. Currently, GitHub has these libraries;
  2. Use autohidemenubar: true, but pressing ALT will bring up the menu

8. Communication between windows.

  1. Main process creation window

Configure preload.js to mount the communication method to the window

 *This is the preload for the window communication example,
 *The preload execution order is before the window JS execution order
import { ipcRenderer, remote } from 'electron'
const { argv } = require('yargs')

const { BrowserWindow } = remote

//Parent window listens for child window events
ipcRenderer.on('communication-to-parent', (event, msg) => {

const { parentWindowId } = argv
if (parentWindowId !== 'undefined') {
  const parentWindow = BrowserWindow.fromId(parentWindowId as number)
  //Mount to window
  // @ts-ignore
  window.send = (params: any) => {
    parentWindow.webContents.send('communication-to-parent', params)

Create window pass in ID

browserWindow.webContents.on('new-window', (event, url, frameName, disposition) => {
    //Creating a window through browserwindow
    const win = new BrowserWindow({ 
      webPreferences: {
        Additionalarguments: ['-- parentwindow = ${browserwindow. ID}'] // pass the ID of the parent window
  1. Parent child window

It’s not as troublesome as the above. Just configure preload and implement it

import { remote, ipcRenderer } from 'electron'

//Parent window listens for child window events
ipcRenderer.on('communication-to-parent', (event, msg) => {

const parentWindow = remote.getCurrentWindow().getParentWindow()
// @ts-ignore
window.sendToParent = (params: any) =>
  parentWindow.webContents.send('communication-to-parent', params)
  1. Rendering process create window

Rendering process communication is very simple. Through window. Open, window. Open will return awindowObjectReference
You can communicate through PostMessage. And window. Open supports the configuration of upload.

9. Window full screen problem.

It’s OK to use the button full screen and exit full screen, but it’s not OK to first click the full screen in the upper left corner and then use the button to exit full screen. Because we can’t know whether the current state is full screen or not.

Configure preload and use the full screen API of electron

import { remote } from 'electron'

const setFullScreen = remote.getCurrentWindow().setFullScreen
const isFullScreen = remote.getCurrentWindow().isFullScreen

window.setFullScreen = setFullScreen
window.isFullScreen = isFullScreen

10. In the MacOS development environment, there may be the problem of file reading permission.

In MacOS, we start the electron application, which is outside the application folder and runs on a read-only disk image. For security reasons, users need to have their own authorization, and electron util makes a good encapsulation. have access toelectron-util  InenforceMacOSAppLocation  method. This documentelectron-util

const { app, BrowserWindow } = require('electron')
const { enforceMacOSAppLocation } = require('electron-util')

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {

app.on('activate', function () {
  if (BrowserWindow.getAllWindows().length === 0) {

Enforcemacosapplocation method encapsulation

'use strict';
const api = require('./api');
const is = require('./is');

module.exports = () => {
	if (is.development || !is.macos) {

	if (api.app.isInApplicationsFolder()) {

	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) {

		conflictHandler: conflict => {
			if (conflict === 'existsAndRunning') { // Can't replace the active version of the app
					type: 'error',
					message: `Another version of ${api.app.getName()} is currently running. Quit it, then launch this version of the app again.`,
					buttons: [


			return true;

If you encounter electron related problems, you can comment on them. We can solve them together and grow together.

Interested in electron? Please pay attention to our open source projectsElectron PlaygroundTo get you started, electron.

Every Friday, we will select some interesting articles and news to share with you, to nuggets to pay attention to our workXiaoqian weekly

We are the front-end technical team of tal.
We will often share with you the latest and coolest technical knowledge of the industry.
WelcomeZhihuNuggetsSegmentfaultCSDNBrief bookOpen source ChinaBlog GardenFocus on us.