关于html:Electron-PlaygroundElectron-窗口问题汇总

7次阅读

共计 5106 个字符,预计需要花费 13 分钟才能阅读完成。

作者: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。

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


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

正文完
 0