Core concepts
Clipboard
The clipboard module allows you to read and write text to the system clipboard. This allows you to easily copy and paste text from and to an application.
Let's think about some use-cases for this:
- You could copy text from a website and paste it into a text editor
- You could copy text from a document and execute a
fetch
request, using the copied text as search parameter - You could
fetch
a JSON file and copy the content to the clipboard, so you have it right at your fingertips to manually paste it where you need it - You could copy text from a file, translate it via an external API and copy the translated text back to the clipboard
- and so on...
Remarks
Please be aware that the clipboard API does not copy text you selected on screen. The clipboard API sets and retrieves text from the system clipboard programmatically.
This means that you can set and retrieve the clipboard text in your code:
const {clipboard} = require("@nut-tree/nut-js");
(async () => {
await clipboard.setContent("Hello World!");
const text = await clipboard.getContent();
console.log(text); // Hello World!
})();
If you want to copy selected text you'll have to use the keyboard module to copy the text via keyboard shortcut, e.g. on Windows Ctrl + C
.
const {keyboard, Key, clipboard} = require("@nut-tree/nut-js");
(async () => {
await keyboard.pressKey(Key.LeftControl, Key.C);
await keyboard.releaseKey(Key.LeftControl, Key.C);
const text = await clipboard.getContent();
console.log(text); // Hello World!
})();
The same holds true for the other way round:
const {keyboard, Key, clipboard} = require("@nut-tree/nut-js");
(async () => {
const text = await clipboard.setContent("We're using the clipboard!");
await keyboard.pressKey(Key.LeftControl, Key.V);
await keyboard.releaseKey(Key.LeftControl, Key.V);
})();