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

标签 javascript pdf electron docx

我正在用HTML和Javascript构建Electron应用程序。我希望该应用程序打开下载的文件,例如PDF,DOCX等在外部标准应用程序(如Adobe Reader和Word)中自动运行。是否有一个简单的Javascript函数来实现这一目标,或者是一种更好的方法?现在,Electron会打开下载对话框,就像在Chrome中一样。不幸的是,我没有太多的Java经验,因此,如果您认为这是一个过于简单的问题,请向我表示歉意。

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)

  }

最佳答案

您可以使用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}`)
    }
  })
})

});



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

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

关于javascript - 如何使Electron在外部应用程序中自动打开下载的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56255956/

相关文章:

javascript - 在 Javascript 中使用普通函数传递数据映射

javascript - 将 MathJax 渲染成 PDF

image - 将长图像转换为页面 pdf

javascript - jsPDF浏览器死亡

linux - 如何在 Linux 中安装 Sqelectron?

javascript - 使用 php 和 javascript 将数据插入数据库

javascript - JSON - 如何将普通格式转换为json格式?

javascript - 如何在 JSON 对象中存储 JSON 字符串而不导致语法错误?

python - 我该怎么做,以便一次只有一个线程可以查看本地json文件

chromium - Electron ( Chrome )禁用网络安全