Как заставить Electron автоматически открывать загруженные файлы во внешнем приложении? - PullRequest
0 голосов
/ 22 мая 2019

Я создаю приложение Electron с использованием HTML и Javascript.Я хочу, чтобы приложение автоматически открывало загруженные файлы, например PDF, DOCX и т. Д., Во внешнем стандартном приложении, таком как Adobe Reader и Word.Есть ли простая функция 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)

  }

1 Ответ

1 голос
/ 22 мая 2019

Вы можете перехватить загрузки, используя событие 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...