Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current clipboard content? [closed]

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?

like image 750
Gabriele Cirulli Avatar asked Sep 26 '22 13:09

Gabriele Cirulli


People also ask

How do I view the contents of my clipboard?

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.

How to get clipboard history in javascript?

const text = await navigator. clipboard. readText();

What is navigator clipboard?

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.


1 Answers

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

like image 122
iuliu.net Avatar answered Oct 07 '22 13:10

iuliu.net