0

Using the Clipboard API in Javascript

 2 years ago
source link: http://www.js-craft.io/blog/using-the-clipboard-api-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using the Clipboard API in Javascript

Ever wonder how sites like google docs are able to put content into your clipboard without you manually need to select all text and hitting ctrl+c?

Screen-Shot-2021-07-28-at-12.01.36-PM-1.png

Well, this is done via the Javascript Clipboard API. You get access to it through the navigator.clipboard object.

If you want to store something in the user clipboard we will use the clipboard.writeText() method. Given that we don't know for sure how much it will take until that info is transferred the operation is async therefore the writeText() will return a promise that will be resolved when the transfer has been finalized.

navigator.clipboard.writeText(SOME_VALUE)
    .then(() => alert("Text is now stored your cliboard!"))

The same applies when reading data from the user clipboard.

navigator.clipboard.readText()
    .then(value => alert("Read:" + value))

Both methods are fully supported in all browsers.

Btw, using the navigator object you can also use the navigator object to detect if we are on a 3g, 4g or Wifi. Happy coding!

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK