【问题标题】:Capturing save and cancel event on window.open() in electron在电子中捕获 window.open() 上的保存和取消事件
【发布时间】:2018-06-30 23:12:02
【问题描述】:

我正在像这样在 js 中本地保存文件

var win = window.open(appConfig.server_url + '/v1/discussion/files/download/chat' + '/' + params);

在浏览器上这会打开一个新选项卡并下载文件并关闭选项卡,但在电子上这会打开一个文件保存对话框,如下所示:

所以我想在 js 中捕获保存和取消事件,以便在单击保存时用户应该收到 “下载成功” 消息,并且在取消时不会发生任何事情。

【问题讨论】:

  • 请出示您的代码。
  • 当点击保存按钮时,这个 window.open 被调用,没有其他东西会影响流程。

标签: javascript electron windows-10 dom-events


【解决方案1】:

您可以向session 注册监听器以捕获'will-download' 事件。在回调中,您可以访问当前的DownloadItem,并且可以对它做任何您想做的事情。

电子docs example:

// In the main process.
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.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')

  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')
    } else {
      console.log(`Download failed: ${state}`)
    }
  })
})

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多