【问题标题】:Electron: Drag and Drop a file on the iconElectron:在图标上拖放文件
【发布时间】:2019-09-12 06:13:43
【问题描述】:

对于 Electron 应用程序,是否可以像使用普通桌面应用程序一样通过在应用程序图标上拖动文件来打开文件?

使用其他地方的代码,我可以打开一个被拖到文档窗口的文件:

document.ondragover = document.ondrop = (event) => {
    event.preventDefault();
};

document.body.ondrop = (event) => {
    openFile(event.dataTransfer.files[0].path.toString());
    event.preventDefault();
};

我希望能够通过将文件拖到应用程序图标本身上来打开文件。

在某些情况下,这也意味着启动尚未运行的应用程序。

【问题讨论】:

  • 你的意思是把它拖到桌面图标上吗?拖动文件的路径将作为参数包含在内,您应该通过 process.argv 处理。
  • @hijleh 如果应用程序已经在运行,你如何回应?
  • 查看我的回答了解更多详情

标签: windows macos drag-and-drop electron


【解决方案1】:

拖动文件的路径将作为命令行参数传递。您可以使用process.argv 访问命令行参数。

const { app } = require('electron')

// You can get the dragged file's path like this
if (process.argv.length >= 2) {
    const filePath = process.argv[1]
    handleFile(filePath)
}

// If you only allow a single instance of your application to be running
// you should use the 'second-instance' event to handle the case if your app is already running
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, argv, workingDirectory) => {
      // Someone tried to run a second instance
      // Handle argv here
      if (argv.length >= 2) {
          const filePath = argv[1]
          handleFile(filePath)
      }
  })
}

function handleFile(filePath) {
 // handle the file as you want
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多