electron踩坑系列之一

前言

以electron作为基础框架,已经开发两个项目了。第一个项目,我主要负责用react写页面,第二项目既负责electron部分+UI部分。

做项目,就是踩坑, 一路做项目,一路踩坑,坑多不可怕,就怕忘记坑。

坑前准备

项目模板

开发,当然就需要搭建项目,搭建项目github上有不少模板。

你可以去 awesome-electronboilerplates部分看到比较流行的模板。
比如:
electron-react-boilerplate
electron-vue
electron-quick-start
electron-boilerplate

用模板相当于上高速,嗖嗖的飞起,不错的选择。
这些模板基本都是把静态页面和electron部分的开发,集成到一个项目里面,有利有弊。

我们项目采用的是分离式的:
electron部分: 负责提供能力,比如读写文件,操作注册表,启动和挂关闭第三方程序,网络拦截,托盘等
UI部分: 绘制页面,必要的时候调用electron封装的能力。

到这里, electron部分与UI部分的交互,我们打开窗体的时候,
nodeIntegration是设置为false的,所有的通讯都是通过一个所谓的bridge来连接的。

bridge通过preload的属性注入,起到了一定的隔离。

我们项目均采用TS开发
前后端两个项目都是基于TS开发,好处不用说。
问题在于,如何将bridge部分友好的提供给UI部分。
也很简单,typescript 编译的时候,其实有一个declaration的选项。
基于bridge单独起一个配置文件,里面仅仅include需要的文件,执行build的,再拷贝到UI项目里面,UI项目就能得到友好的提示。

主进程和渲染进程的通讯

electron-better-ipc 是不错的选择,原理就是利用EventEmitter的once特性,内部的每次通讯都是一个新的事件类型。
对于超时和错误捕捉,主向多个渲染进程发消息,都还得自己去增强。

我们是自己维护了一个调用信息, 发送的数据有一个key来标识,目前看来,还算稳定。

日志

electron-log是不错的选择,简简单单的就能记录主进程和渲染进程的日志。
但是不能记录node唤起的子进程的日志,真要想记录,子进程单独通知到外面,外面记录。或者单独自己弄一个写子进程的日志也没问题的。

日志多了肯定不行,就会有日志轮转。目前这个库,好像有一个简单粗暴的轮转策略,肯定是不够用的。

具体的可以到File transport

function archiveLog(file) {
  file = file.toString();
  const info = path.parse(file);

  try {
    fs.renameSync(file, path.join(info.dir, info.name + '.old' + info.ext));
  } catch (e) {
    console.warn('Could not rotate log', e);
  }
}

我这里就贴一段基本可用的, deleteFiles自定去实现,你可以保留几个文件,保留几天的文件,都是可以的。

// 50M
log.transports.file.maxSize = 50 * 1024 * 1024;

log.transports.file.archiveLog = function archiveLog(file: string) {
    file = file.toString();
    const info = path.parse(file);

    try {
        // 重命名
        const dateStr = getDateStr();

        const newFileName = path.join(info.dir, `${info.name}.${dateStr}${info.ext}`);

        console.log("archiveLog", file, newFileName);

        fs.renameSync(file, newFileName);

        // 删除旧文件
        deleteFiles(info.dir)
    } catch (e) {
        console.error('Could not rotate log', e);
    }
}

持久化的数据

electron-store 很不错。

我们采用的是内存数据 + config.json的模式,实际上本质没变。
如果是窗体之间的页面之间要共享数据,其实用localStorage和sessionStorage,indexedDB都是不错的选择。

入坑和填坑

应用启动页面空白

简单的排查顺序
1.浏览器打开网页地址
2.如果不能打开, 查看网络是否正常
3.网络正常,ping域名
4.ping 不通, 说明域名有问题
5.打开 %appdata%, 查看日志是不是有打开页面超时的提示
6.关闭 360安全卫士,重新打开主播端

最后一条是关键哈。
不签名,不过百的情况下,升级启动都很可能被360拦截。

如上都还不行,检查系统的版本是不是低于等于wind7 SP1
如果是

  1. 安装最新版的.NET Framework: https://dotnet.microsoft.com/download/dotnet-framework
    相关issue: https://github.com/electron/electron/issues/25186
  2. 降低你的electron版本,要降低到多少,这个我也不好说,也许6.0以下吧。

原生模块.node结尾的文件引用报错

build时指定electron版本,headers头文件路径
https://www.electronjs.org/docs/tutorial/using-native-node-modules

这个官方是有很明确的指出来的

开发时正常,打包后提示,cannot find moudule "xxxx"

使用npm 安装,不用cnpm。
这是和不同的安装方式,文件目录结构不一致。
当然开发的时候,你是可以使用cnpm或者yarn的。
我没有尝试使用打包做一些修改让cnpm有效,你们要是知道,可以留言告诉我哈。

the specified module could not be found. "................\xxxx.node"

这个和上面那个有点类似,但是又不一样的。 下面这种情况可能是.node模块需要引用一些dll文件,却没有。比如常见的msvcr120.dll,msvcr110.dll,msvcp120.dll,msvcp110.dll这些文件,你把这些放到.node的同级目录。至于怎么区分32位和64位,哈哈,我知道您懂。

The specified module could not be found.

AppData\Local\Temp\xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.tmp.node

https://stackoverflow.com/questions/41253450/error-the-specified-module-could-not-be-found
有提到大致的原生就是 .node缺少一些dll库。可以使用 http://www.dependencywalker.com/ 检查缺少啥

我做了四种尝试:

  • 安装 visual-c 组件 failed
  • 复制dll到asar同目录 failed
  • electron-builder 设置asar为false ok
  • C++模块文件夹移动asar包体外 ok

后两种是有效的,而且这个问题可能只出现在某些机器上。某些机器是正确的,某些机器却不正确。

electron-builder 打包后卸载或者更改程序中的发布者名称问题

首先说这个发布者是哪个字段,其实是package.json里面的author字段的name属性,当然可以有多种写法。

如果的你名字类似 牛潮(北京)有限公司,那么你打包出来就只会剩下 牛潮两个字,是不是有一些神奇。

这个其实是 electron-builder库packages\app-builder-lib\src\util\normalizePackageData.ts 或者额是 normalize-package-data库做了一些操作。
unParsePerson之后再parsePerson,英文括弧后面的东西就没了。怎么办,我现在是手动找到修改一下。

  function fixPeople(data: any) {
    modifyPeople(data, unParsePerson)
    modifyPeople(data, parsePerson)
  },

function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name || ""
  var u = person.url || person.web
  var url = u ? (" ("+u+")") : ""
  var e = person.email || person.mail
  var email = e ? (" <"+e+">") : ""
  return name+email+url
}

function parsePerson (person) {
  console.log("parsePerson person", person)
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
  var url = person.match(/\(([^\)]+)\)/)
  var email = person.match(/<([^>]+)>/)
  var obj = {}
  if (name && name[0].trim()) obj.name = name[0].trim()
  if (email) obj.email = email[1];
  if (url) obj.url = url[1];
  return obj
}

electron-builder打包签名问题

他这个打包可以签名,但是要你提供.pfx文件和密码。
这就有点老火了,公司的这两个东西一般不会轻易给你。
要么你们有统一的打包中心,那就没问题。
可惜我们公司只有统一的签名中心,签名之后,exe文件是有变化的,比如大小和最后修改时间,这就会导致更新的时候,检查hash值会失败。

问题不大:

  1. 我们先到electron-buider的源码里面packages\app-builder-lib\src\util\hash.ts找到hash值生成的方法,这个hash值会被写入latest.yml文件里面
  2. 本地打包好exe
  3. 去签名中心签名,并覆盖本地的exe
  4. 用hash.ts相同的方式再计算得到hash值
  5. 回写这些值到latest.yml文件

基本就是这样啦。

这里送一段基本能用的代码吧:


import { createHash } from "crypto"
import { createReadStream, statSync , readFileSync, writeFileSync } from "fs"
import path from "path";
import YAML from "yaml";

const jsonConfig = require("../package.json");
const version = jsonConfig.version;


const exeFilePath = path.join(__dirname, `../packages/${version}.exe`);
const yamlFilePath = path.join(__dirname, "../packages/latest.yml");
const jsFilePath = path.join(__dirname, "../packages/latest.js");

const bakYamlFilePath =  path.join(__dirname, `../packages/latest.bak.yml`);

// packages\app-builder-lib\src\util\hash.ts
function hashFile(file: string, algorithm = "sha512", encoding: "base64" | "hex" = "base64", options?: any): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      const hash = createHash(algorithm)
      hash.on("error", reject).setEncoding(encoding)
  
      createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ })
        .on("error", reject)
        .on("end", () => {
          hash.end()
          resolve(hash.read() as string)
        })
        .pipe(hash, { end: false })
    })
}

function getFileSize(path: string){
    const state = statSync(path);
    return state.size;
}


function getYAML(path: string){
  const file = readFileSync(path, 'utf8')
  const data = YAML.parse(file);
  return data;
}

function saveYAML(path:string, content: any){
  writeFileSync(path,  YAML.stringify(content))
}

function saveJS(path:string, content: string){
  writeFileSync(path,  content)
}


;(async function updateLatestYML(){
  try{
    const hash = await hashFile(exeFilePath);
    const size = getFileSize(exeFilePath);

    console.log("hash:", hash);
    console.log("size:", size);

    const yamlData = getYAML(yamlFilePath);
    saveYAML(bakYamlFilePath, yamlData);
    console.log("yamlData:before", yamlData);


    const name = `${version}.exe`

    yamlData.version = version;
    const file = yamlData.files[0];
    file.url = name;
    file.sha512 = hash;
    file.size = size;

    yamlData.path = name;
    yamlData.sha512 = hash;

    console.log("yamlData:after", yamlData);
    saveYAML(yamlFilePath, yamlData);

    saveJS(jsFilePath, `window._lastest=${JSON.stringify(yamlData)}`);

  }catch(err){
    console.log("update latest.yml 失败", err);
  }
})();

本地测试electron-updater的问题

https://www.electron.build/auto-update#debugging
https://stackoverflow.com/questions/51003995/how-can-i-test-electron-builder-auto-update-flow
https://github.com/electron-userland/electron-builder/issues/3053#issuecomment-401001573
虽然官方建议单独使用一个啥server来着,总让人觉得有点复杂,其实还是可以直接在开发中测试的。

  1. 复制 resources\app-update.yml,重名命令dev-app-update.yml
  2. build时复制到dist目录

代码层面做一点小修改

function checkUpdate() {
    // 开发环境
    if(!app.isPackaged){
        return autoUpdater.checkForUpdates();
    }
    return autoUpdater.checkForUpdatesAndNotify();
}

这里还要额外注意

  1. 版本检查的是electron的版本,所以latest.yml的版本要大
  2. 缓存的默认目录为 %localappdata%/{默认是package.json里面name}-updater/pending,和electron-builder里面的是指有关

404返回的页面不会触发did-fail-load

你想想,我们很多时候打开的是远程的网页地址。 如果返回的状态码是404,明显不是我们想要的,如果我们依据did-fail-load事件去判断,是否加载失败,当然是不满足我们的需求的。

我们需要在远程加载失败的时候,使用本地的默认页面去给用户一些提示信息,以及可以关闭窗体。

这个时候就要did-frame-navigate出场,根据httpResponseCode的状态去使用本地备用页面了。

 win.webContents.on("did-frame-navigate",  (event: Electron.Event, url: string, httpResponseCode: number, httpStatusText: string, isMainFrame: boolean, frameProcessId: number, frameRoutingId: number) =>{
            console.log("did-frame-navigate", httpResponseCode, httpStatusText);
            if(httpResponseCode >= 400 && !this.isUsedFailedPage){
               return this.useFailedPage();
            }
        });

页面ctrl + r会被刷新等

ctrl + r 刷新页面
ctrl + shift + i 打开开发者工具

哈哈,要是不小心被用户打开是不是有点搞笑了。

你可以写一个配置到配置文件,默认不允许打开,当需要去现场排查问题的时候,可以打开。 被打开肯定有危险,但是方便调试。

我这里做的页面拦截

const BLACK_LIST = ["KeyI", "KeyR"];
function preventForceRefreshAndTool() {
    const env = process.env.ENV;
    console.log("process.env.ENV", process.env.ENV);
    if (env !== "prod") {
        return console.log("非产线环境,允许刷新和打开开发者工具");
    }

    window.addEventListener('keydown', (e: KeyboardEvent) => {
        const { ctrlKey, code, shiftKey } = e;

        console.log("keydown", e);
        // ctrl +  r
        // crtl + shift + i
        if (ctrlKey && shiftKey && BLACK_LIST.includes(code)) {
            console.log("globalShortcut:被阻止", ctrlKey, shiftKey, code);
            e.preventDefault();
        }
    
    }, false);
}

electron拦截

      win.webContents.on('before-input-event', (event, input) => {
          console.log('before-input-event', input.control, input.shift, input.key)
          if (input.control && KEY_BLACK_LIST.includes(input.key.toUpperCase())) {
            event.preventDefault()
          }
     });

结语

到这里,老板已经走到我的身后,我默默的说,我总结一下问题。
老板说: 好样子的,不过你为嘛在上班时间写博客。
我: 流汗,各位,拜。

其他

排查问题

Electron 常见问题
electron issues
Electron 常见问题收录
Electron 常见问题收录II
electron 问题收集

其他工具类

electron-util 工具类
electron-router

posted @ 2021-04-06 18:29  -云-  阅读(3600)  评论(0编辑  收藏  举报