如何从session.on('will-download')之外调用downloadItem.pause()和downloadItem.pause()?

时间:2017-09-18 09:21:28

标签: electron

我正在尝试使用电子库实现暂停和恢复功能。我怎么能调用item.pause out of session.on('will-download')因为它是session.on('will-download')中的item的功能,还是来自任何其他方式?

  var url, path, filename;
  ipcMain.on(‘item:file’, function(e, file) {
    if(file.msg === ‘d’){
     console.log(file);
     url = file.url;
     path = pathLib.join(__dirname, file.path);
     filename = file.filename;
     contents.downloadURL(url);
    }
    if(file.msg === ‘p’){
     item.pause();
    }
    if(file.msg === ‘r’){
     item.resume();
    }

    contents.session.on('will-download', (event, item, contents) => {  
     // Set the save path, making Electron not to prompt a save dialog.
     path = `${path}${filename}`;
     item.setSavePath(path);
     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()} out of ${item.getTotalBytes()}`);
           var percentage  = (item.getReceivedBytes()/item.getTotalBytes())*100;
           var progress = {'rBytes':item.getReceivedBytes(), 'tBytes':item.getTotalBytes(), 'p':percentage};
           contents.send('item:progress', progress);
         }
       }
     });
     item.once('done', (event, state) => {
       if (state === 'completed') {
         console.log('Download successfully');
       } else {
         console.log(`Download failed: ${state}`);
       }
    });
  });
});

1 个答案:

答案 0 :(得分:0)