I'd like to know a way to make my script detect the content of the clipboard and paste it into a text field when the page is opened, with no input from the user. How can it be done?
To get to your clipboard history at any time, press Windows logo key + V. From the clipboard history, you can paste and pin frequently used items by choosing an individual item from your clipboard menu. Pinning an item keeps it from being removed from the clipboard history to make room for new items.
const text = await navigator. clipboard. readText();
clipboard. The Clipboard API adds to the Navigator interface the read-only clipboard property, which returns the Clipboard object used to read and write the clipboard's contents. The Clipboard API can be used to implement cut, copy, and paste features within a web application.
Use the new clipboard API, via navigator.clipboard
. It can be used like this:
With async/await syntax:
const text = await navigator.clipboard.readText();
Or with Promise syntax:
navigator.clipboard.readText()
.then(text => {
console.log('Pasted content: ', text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
Keep in mind that this will prompt the user with a permission request dialog box, so no funny business possible.
The above code will not work if called from the console. It only works when you run the code in an active tab. To run the code from your console you can set a timeout and click in the website window quickly:
setTimeout(async () => {
const text = await navigator.clipboard.readText();
console.log(text);
}, 2000);
Read more on the API and usage in the Google developer docs.
Spec
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With