当我尝试在index.js 中执行自定义电子标题栏时,出现错误。
我的index.js代码:
const { app, BrowserWindow } = require('electron');
const customTitlebar = require('custom-electron-titlebar');
var path = require('path');
let mainWindow;
function onClosed() {
mainWindow = null;
}
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 350,
height: 210,
frame: false
})
new customTitlebar.Titlebar({
backgroundColor: customTitlebar.Color.fromHex('#444')
});
customTitlebar.setTitle('asd')
mainWindow.setMenuBarVisibility(false)
mainWindow.loadURL(`file:\\${__dirname}\\index.html`)
mainWindow.on('closed', onClosed)
});
如果我运行这个,我会收到此错误:
ReferenceError: navigator is not defined
at Object.<anonymous> (<mypath>\node_modules\custom-
electron-titlebar\lib\browser\browser.js:130:19)
at Module._compile (internal/modules/cjs/loader.js:968:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:986:10)
at Module.load (internal/modules/cjs/loader.js:816:32)
at Module._load (internal/modules/cjs/loader.js:728:14)
at Module._load (electron/js2c/asar.js:717:26)
at Function.Module._load (electron/js2c/asar.js:717:26)
at Module.require (internal/modules/cjs/loader.js:853:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (D:\Programing\Projects\ElectronProjects\Calculator\node_modules\custom-
electron-titlebar\lib\common\dom.js:7:17)
我导入了“自定义电子标题栏”,但它不起作用。
navigator
是一个浏览器API,仅在Renderer进程中可用。您正在从主进程调用 require('custom-electron-titlebar')
,该进程无权访问该 API。
您必须从渲染器进程中运行导入库或将其添加到 HTML 脚本标记中,按照 custom-electron-titlebar
的
使用文档。
有关 Electron 流程模型的更多信息,您可以查看 docs。
主流程通过创建
实例来创建网页。每个BrowserWindow
实例在其自己的渲染器进程中运行网页。当BrowserWindow
实例被销毁时,相应的渲染器进程也会终止。BrowserWindow
主进程管理所有网页及其对应的渲染器进程。每个渲染器进程都是隔离的,只关心其中运行的网页。
在网页中,不允许调用原生GUI相关的API,因为在网页中管理原生GUI资源是非常危险的,很容易泄漏资源。如果要在网页中执行 GUI 操作,网页的渲染进程必须与主进程通信以请求主进程执行这些操作。
创建一个 preload.js 文件并将该文件加载到主窗口的 webPreferences 对象中。
mainWindow = new BrowserWindow({
frame: false,
webPreferences: {
devTools: true,
enableRemoteModule: true,
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, "preload.js"),
},
});
并将此代码放入 preload.js 文件中
window.addEventListener("DOMContentLoaded", () => {
const { Titlebar } = require("custom-electron-titlebar");
new Titlebar({
backgroundColor: "teal",
titleHorizontalAlignment: "left",
icon: "./logo.png",
});
});