Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

jquery - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...