4

I'm currently working on a react/electron app and I want to be able to copy a file that's outside the app (could be any file type) using ctrl+c or right click copy.

How can I retrieve that file's name and path inside my app? I've tried navigator.clipboard.readText() and .read() and haven't had any luck.

cachique
  • 1,150
  • 1
  • 12
  • 16

1 Answers1

1

Unfortunately in Electron, clipboard is still highly platform-dependant requiring different code depending on which platform you're running. Here's a snippet for a single file to get you started. If you need access to multiple files, see this snippet.

const { clipboard } = require('electron')

let text = null
if(process.platform === 'darwin') {        // MacOS
  text = clipboard.read('public.file-url')
} else {                                   // Windows
  text = clipboard.readBuffer('FileNameW').toString('ucs2')
}                                          // TODO: Linux
console.log(text);

Depending on your presentation, you may need to convert to a human readable format (e.g. file:/// vs. C:\, etc)

tresf
  • 7,103
  • 6
  • 40
  • 101
  • 1
    Thanks! This is exactly what I needed. I tried the multiple file approach for windows and it gave me all the URLs but in some kind of weird string with all sorts of extra spaces and characters. But all I need to do now is figure out a way to parse through it. – JMArmbruster Jun 23 '21 at 21:19
  • 1
    Regarding the `ucs2` encoding: https://stackoverflow.com/questions/8715980/javascript-strings-utf-16-vs-ucs-2. Regarding getting rid of the URI formatting altogether (e.g. readability on Windows) https://www.npmjs.com/package/file-uri-to-path. – tresf Jun 24 '21 at 16:12