【发布时间】:2021-01-02 18:05:53
【问题描述】:
当我在 Windows 10 上构建 npm start 应用程序时,它无法正常运行,而在 macOS 上运行良好。
package.json
{
"name": "SimpleTimer",
"version": "1.0.0",
"productName": "SimpleTimer",
"copyright": "",
"description": "",
"main": "main.js",
"scripts": {
"start": "node_modules/.bin/electron .",
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"electron": "^10.1.2"
}
}
我收到以下错误消息。
TypeError: ipcMain.handle is not a function 此处适用:
main.js
ipcMain.handle("ipc-timer-start", () => {
if ( isWorking === true ) {
return true
}
else {
StartTimer();
isWorking = true;
}
return true;
});
这个函数是来自ipcRenderer.invoke()的ipc通信的接收者,写在preload.js。就是下面源码中TimerStart api中的invoke()方法。
preload.js
const { contextBridge, ipcRenderer} = require("electron");
contextBridge.exposeInMainWorld(
"api", {
TimerStart: () =>
ipcRenderer.invoke("ipc-timer-start") /*** HERE ***/
.then(result => result)
.catch(err => console.log(err)),
TimerStop: () => ipcRenderer.send("ipc-timer-stop"),
TimerReset: () => ipcRenderer.send("ipc-timer-reset"),
DisplayTimer: (channel, listener) => {
ipcRenderer.on("ipc-display-timer", (event, arg) => listener(arg));
}
}
);
当然,preload.js 是在创建 BrowserWindow 时指定的。
main.js
mainWindow = new BrowserWindow({
title: config.name,
width: 1024,
height: 640,
minWidth: 1024,
minHeight: 640,
webPreferences: {
worldSafeExecuteJavaScript: true,
nodeIntegration: false,
contextIsolation: true,
preload: __dirname + '/preload.js' /*** HERE ***/
}
});
跳过此错误消息对话框后,我使用 DevTools 进行了检查,看起来 preload.js 不是从 Unable to load preload script: 的语句中加载的。
鉴于这些陈述,preload.js 似乎没有正确包含在构建中,我该怎么办?
再一次,它在 macOS 上运行良好,但由于这些问题,它在 Windows 10 上无法正常运行。
【问题讨论】:
标签: javascript node.js windows electron preloadjs