Electron in Practice: Clipboard
Preface
Electron provides operations for reading from and writing to the system clipboard.
See: https://www.electronjs.org/docs/latest/api/clipboard
Process
clipboard is supported in the main process and in renderer processes without sandbox enabled.
const { clipboard } = require('electron');
System
Most clipboard APIs support Windows, Mac, and Linux.
On Linux, there is a selection clipboard.
You can use the type parameter to access the selection clipboard content.
// default
clipboard.readText();
// Linux selection clipboard
clipboard.readText('selection');
API
The read/write related APIs in clipboard are as follows
// text
clipboard.readText();
clipboard.writeText(text);
// html
clipboard.readHTML();
clipboard.writeHTML(markup);
// image
clipboard.readImage();
clipboard.writeImage(image);
// rtf
clipboard.readRTF();
clipboard.writeRTF(text);
// bookmark, Windows and Mac only
clipboard.readBookmark();
clipboard.writeBookmark(title, url);
// find text, Mac only
clipboard.readFindText();
clipboard.writeFindText(text);
Other APIs
// Clear clipboard
clipboard.clear();
// Get supported clipboard formats, e.g.: [ 'text/plain', 'text/html' ]
clipboard.availableFormats();
sandbox
As mentioned above, clipboard is not supported in renderer processes with sandbox disabled.
So how do you operate the clipboard in a renderer process without sandbox enabled?
Via IPC
One approach is to use IPC between the renderer process and the main process to operate the clipboard.
In the renderer process
// preload.js
const { ipcRenderer } = require('electron');
ipcRenderer.send('clipboard-write-text', text);
In the main process
// main.js
const { ipcMain, clipboard } = require('electron');
ipcMain.on('clipboard-write-text', (_, text) => {
clipboard.writeText(text);
});
Via browser clipboard API
Browsers support navigator.clipboard.
See: https://developer.mozilla.org/zh-CN/docs/Web/API/Clipboard_API
In the renderer process
navigator.clipboard.readText().then((clipText) => {
console.log(clipText);
});
Comparison
1. The IPC approach is transparent to the user, but may cause lag if the clipboard content is large.
2. The navigator.clipboard approach triggers a security authorization prompt, requiring user permission before use.