You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中Angular桌面应用如何在新窗口打开PDF?

解决Electron中打开PDF出现双窗口的问题

问题根源是:你的window.open(url, "_blank")会触发Electron默认创建一个空白窗口,同时你在will-download事件里又手动创建了新窗口加载PDF,导致出现两个窗口。需要拦截默认的空白窗口创建,将下载与窗口打开流程合并。

主进程修改代码示例

  1. 先添加变量存储待打开PDF的窗口配置,再拦截window.open请求:
const { app, BrowserWindow } = require('electron');
let mainWindow;
let pendingPdfWindowOptions = null;

// 假设width、mWidth、height、mHeight是你已定义的窗口尺寸变量

function createWindow() {
  mainWindow = new BrowserWindow({ /* 你的主窗口配置 */ });

  // 拦截window.open请求,阻止默认空白窗口创建
  mainWindow.webContents.setWindowOpenHandler((details) => {
    // 识别PDF请求(可根据实际URL规则调整)
    if (details.url.endsWith('.pdf')) {
      // 保存窗口配置
      pendingPdfWindowOptions = {
        title: details.url.split('/').pop(),
        x: width - mWidth - 3,
        y: height - mHeight - 3,
        width: mWidth,
        height: mHeight,
        minWidth: mWidth,
        minHeight: mHeight,
        useContentSize: false,
        icon: __dirname + '/src/logo.ico',
        minimizable: false,
        maximizable: true,
        fullscreen: false,
        frame: true,
        resizable: true,
        movable: true,
        alwaysOnTop: false,
        webPreferences: {
          nodeIntegration: true,
          zoomFactor: 1.0
        }
      };
      // 阻止默认窗口创建
      return { action: 'deny' };
    }
    // 非PDF链接允许默认打开
    return { action: 'allow' };
  });

  // 处理PDF下载与打开
  mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
    const pdfFilename = item.getFilename();
    const savePath = `${app.getPath("temp")}/${pdfFilename}`;
    log.info(`item: ${pdfFilename}	URL: ${savePath}`);
    item.setSavePath(savePath);

    item.once('done', (event, state) => {
      // 仅在下载完成且有等待的窗口配置时创建窗口
      if (state === 'completed' && pendingPdfWindowOptions) {
        pendingPdfWindowOptions.title = pdfFilename;
        const subWindow = new BrowserWindow(pendingPdfWindowOptions);
        subWindow.removeMenu(null);
        // 用file协议加载本地PDF文件
        subWindow.loadURL(`file://${savePath}`);
        // 重置配置变量,避免后续请求复用
        pendingPdfWindowOptions = null;
      }
    });
  });
}

app.whenReady().then(createWindow);

关键说明

  • 通过setWindowOpenHandler返回{ action: 'deny' },阻止Electron为window.open创建默认空白窗口。
  • 用pendingPdfWindowOptions暂存窗口配置,确保下载完成后只创建一个窗口加载PDF。
  • 下载完成后重置pendingPdfWindowOptions,避免后续请求错误复用配置。
  • 可根据实际业务调整PDF请求的识别逻辑(比如通过响应头Content-Type: application/pdf判断,而不是仅靠URL后缀)。

内容的提问来源于stack exchange,提问作者Dev Minty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:15:44