Electron各版本API变更及版本升级报错汇总

2021-09-30 11:03:24 浏览数 (1)

版本升级注意项

每个版本都有废弃和移除的API,废弃的依旧可以用,所以这里只列一些常用的被移除的API及对应的替换方法。

各版本移除的API

官方文档:https://www.electronjs.org/docs/latest/breaking-changes/#removed-remote-module

14.0

remote模块

The remote module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.

代码语言:javascript复制
// Deprecated in Electron 12:
const { app, dialog } = window.require('electron').remote

替换方式

安装依赖

代码语言:javascript复制
npm install --save @electron/remote

主进程

代码语言:javascript复制
// In the main process:
require('@electron/remote/main').initialize()
//创建每一个窗口后,都要调用
require("@electron/remote/main").enable(win.webContents);

渲染进程

代码语言:javascript复制
// Replace with:
const { app, dialog } = window.require('@electron/remote');

13.0

Extension

代码语言:javascript复制
// Removed in Electron 13
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Replace with
session.defaultSession.loadExtension(path)
代码语言:javascript复制
// Removed in Electron 13
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// Replace with
session.defaultSession.removeExtension(extension_id)
代码语言:javascript复制
// Removed in Electron 13
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Replace with
session.defaultSession.getAllExtensions()

12.0

crashReporter

Removed: crashReporter.getCrashesDirectory()

The crashReporter.getCrashesDirectory method has been removed. Usage should be replaced by app.getPath('crashDumps').

代码语言:javascript复制
// Removed in Electron 12
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')

9.0

<webview>.getWebContents()

This API, which was deprecated in Electron 8.0, is now removed.

代码语言:javascript复制
// Removed in Electron 9.0
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())

错误汇总

require

引用时报错

代码语言:javascript复制
const { ipcRenderer } = window.require('electron');

错误信息

window.require not a function

解决方式

代码语言:javascript复制
webPreferences: {
    nodeIntegration: true,
    enableRemoteModule: true,
    contextIsolation: false,
},

0 人点赞