A JavaScript error occurred in the main process
electron-dl 在处理 will-download 事件时把 webContents 当成必然存在导致的异常
这是 electron-dl 在处理 will-download 事件时把 webContents 当成必然存在导致的异常。启动下载是由 session.downloadURL(...)(或窗口已被关闭)触发时,回调参数 webContents 可能为 null;electron-dl 里会调用 webContents.getOwnerBrowserWindow(),于是报 Cannot read properties of null。 解决 - 调用 electron-dl 时传入窗口对象,不要只传 URL:
- // main process
- const { download } = require('electron-dl');
- async function startDownload(url) {
- const win = BrowserWindow.getFocusedWindow() || mainWindow;
- await download(win, url, { directory: 'D:\\Downloads' });
- }
复制代码 或使用- win.webContents.downloadURL(url); // 有 webContents,不会为 null
复制代码- 自己监听 will-download 时要判空并提供兜底窗口:
- const { session, BrowserWindow } = require('electron');
- session.defaultSession.on('will-download', (e, item, wc) => {
- const win = wc ? BrowserWindow.fromWebContents(wc)
- : BrowserWindow.getFocusedWindow() || mainWindow;
- if (!win) return; // 无窗口时自行处理
- // ...进度/保存路径等逻辑
- });
复制代码- 如果你没直接用 electron-dl,但项目打包里自带它,升级到最新版本或暂时移除/替换 electron-dl。
- 另外,避免在触发下载后立即销毁窗口;若要关闭窗口,等到 item.once('done', ...) 之后再关。
|