DEV Community

Cover image for How to get file path from clipboard in ElectronJS
Khoi Doan (Osbkca)
Khoi Doan (Osbkca)

Posted on

How to get file path from clipboard in ElectronJS

To get file path of a file which you have copied on the your computer through ElectronJS depends on the operating system run the Electron application on.
In this article, I work on two popular operating system MacOs and Windows

On MacOS:

const filePath = clipboard.read('public.file-url').replace('file://', '');
Enter fullscreen mode Exit fullscreen mode

On Windows:

const rawFilePath = clipboard.read('FileNameW');
const filePath = rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '');
Enter fullscreen mode Exit fullscreen mode
import { clipboard } from "electron";
export const getFilePathFromClipboard = () => {
  let filePath = "";
  if (process.platform === "darwin") {
    filePath = clipboard.read("public.file-url").replace("file://", "");
  }

  if (process.platform === "win32") {
    filePath = clipboard
      .read("FileNameW")
      .replace(new RegExp(String.fromCharCode(0), "g"), "");
  }

  return filePath;
};
Enter fullscreen mode Exit fullscreen mode

I used above code for my love app Xclippy

xclippy #osbkca

Top comments (0)