如何让 Electron 在外部应用程序中自动打开下载的文件?

neo*_*ith 0 javascript pdf docx electron

我正在使用 HTML 和 Javascript 构建一个 Electron 应用程序。我希望应用程序在外部标准应用程序(如 Adob​​e Reader 和 Word)中自动打开下载的文件,例如 PDF、DOCX 等。是否有一个简单的 Javascript 函数来实现这个或者更好的方法?现在 Electron 会打开下载对话框,就像在 Chrome 中一样。不幸的是,我对 Javascript 没有很多经验,所以如果这是一个太简单的问题而您无法关注,我深表歉意。

const electron = require ('electron');
const url = require('url');
const path = require('path');

// In the main process.
const { app, Menu, BrowserWindow ,  shell } = require('electron')




// Listen for the app to be ready

app.on('ready', function() {
    // Create new window
    mainWindow = new BrowserWindow({});
    // Load html into window
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }));

    // Build menu from template
    const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
    // Insert menu
    Menu.setApplicationMenu(mainMenu);

    mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
        // Set the save path, making Electron not to prompt a save dialog.
        item.setSavePath('/tmp/save.pdf')// get the filename from item object and provide here according to your logic

      item.on('updated', (event, state) => {
        if (state === 'interrupted') {
          console.log('Download is interrupted but can be resumed')
        } else if (state === 'progressing') {
          if (item.isPaused()) {
            console.log('Download is paused')
          } else {
            console.log(`Received bytes: ${item.getReceivedBytes()}`)
          }
        }
      })
      item.once('done', (event, state) => {
        if (state === 'completed') {
          console.log('Download successfully')
          //Open the document using the external application
          shell.openItem(item.getSavePath());
        } else {
          console.log(`Download failed: ${state}`)
        }
      })
    })
});

// Create menu template 
const mainMenuTemplate = [
    {
        label: 'File',
        submenu: [
            {
                label: 'Quit',
                accelerator: process.platform == 'darwin' ? 'Command+Q' : 'Ctrl+Q',
                click(){
                    app.quit();
                }
            }
        ],

    },
    {
        label: 'View',
        submenu: [
            {
                label: 'Toggle Fullscreen',
                click(){
                    mainWindow.isFullScreen() == true ? mainWindow.setFullScreen(false) : mainWindow.setFullScreen(true)
                }

            }


        ],


    }

];

function toggleFullScreen() {

    mainWindow.setFullScreen(true) ?   mainWindow.setFullScreen(false) :   mainWindow.setFullScreen(true)

  }

Run Code Online (Sandbox Code Playgroud)

Sha*_*n K 6

您可以使用 will-download 事件拦截下载并使用 shell.openItem(); 显示下载的文件;

// In the main process.

const {app, BrowserWindow, Menu ,shell } = electron;

app.on('ready', function() {
    // Create new window
    mainWindow = new BrowserWindow({});
    // Load html into window
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }));

    // Build menu from template
    const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
    // Insert menu
    Menu.setApplicationMenu(mainMenu);
mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
    // Set the save path, making Electron not to prompt a save dialog.
    item.setSavePath('/tmp/save.pdf')// get the filename from item object and provide here according to your loic

  item.on('updated', (event, state) => {
    if (state === 'interrupted') {
      console.log('Download is interrupted but can be resumed')
    } else if (state === 'progressing') {
      if (item.isPaused()) {
        console.log('Download is paused')
      } else {
        console.log(`Received bytes: ${item.getReceivedBytes()}`)
      }
    }
  })
  item.once('done', (event, state) => {
    if (state === 'completed') {
      console.log('Download successfully')
      //Open the document using the external application
      shell.openItem(item.getSavePath());
    } else {
      console.log(`Download failed: ${state}`)
    }
  })
})

});


Run Code Online (Sandbox Code Playgroud)

https://electronjs.org/docs/api/shell

https://electronjs.org/docs/api/download-item