Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to paste from clipboard onclick in Javascript?

The use case is for data entry on a private intranet: Users copy and paste from google docs, dropbox text documents etc and have to paste into a form with many inputs. to speed it up for them, it would be nice if the user could copy and paste from the document, and when they click on the input field, it automatically pastes when they left click.

I've seen some older questions, but it appears that this is (and for good reason) a security risk. however, all the users on the private intranet are aware of this and simply want to save time. is there any browser or technique that would allow this?

also, we can use any browser or environment that supports it. How can I then achieve this functionality to save time?

like image 725
mazing Avatar asked May 31 '18 22:05

mazing


People also ask

Can JavaScript access clipboard?

Accessing the OS clipboard using browser JavaScript has been possible for several years using document. execCommand() .

How do you copy text to clipboard on a button click?

The next most common work-around is to just place the clipboard-bound text into an input field, move the focus to that field and advise the user to press Ctrl + C to copy the text.

How do you copy and paste text in JavaScript?

copy and paste text ; description : when a select some text in textArea , then click for a button to make copy it , when go to another page right click in textarea and choose paste .


1 Answers

The clipboard API is included in Chrome 66. Check the jsfiddle here: https://jsfiddle.net/zm490d6a/

Relevant code is:

async function paste(input) {
  const text = await navigator.clipboard.readText();
  input.value = text;
}

If you are in Chrome 66 or later this will work. However, note that you must give the webpage permission to access the clipboard for security reasons, so the first time you click on the input on that page it will popup asking your permission to access the clipboard. Once you give it access any clicks into the input will paste whatever is on your clipboard.

Here I simply use readText, but you can also use readData for images etc on the clipboard. https://developer.mozilla.org/en-US/docs/Web/API/Clipboard

like image 68
Rob Louie Avatar answered Oct 09 '22 21:10

Rob Louie