DEV Community

Cover image for How to implement copy and paste in a web application
Hillary Chibuko
Hillary Chibuko

Posted on

How to implement copy and paste in a web application

Ever wondered how to implement copy and paste functionality in any of your web applications?
yes , I have
It is pretty much easier than it sounds , we only have to access the navigator.clipboard object to perform this.

1 copy

navigator.clipboard.writeText(e.target.value);

And that's all you need to copy whatsoever to the browsers clipboard

2 paste

This is almost same as the previous
navigator.clipboard.readText().then((text)=>console.log(text))
and there you have it , what you copied in your browsers console.

Easy peazy!!!

Oldest comments (4)

Collapse
 
blackr1234 profile image
blackr1234 • Edited

Both writeText and readText methods are returning Promise objects. Could you post full code that is able to print the copied text in console log?

Collapse
 
peerreynders profile image
peerreynders • Edited
setTimeout(() => {
  navigator.clipboard.readText().then((clipText) => console.log(clipText));
}, 5000);
Enter fullscreen mode Exit fullscreen mode

or

setTimeout(async () => {
  const clipText = await navigator.clipboard.readText();
  console.log(clipText);
}, 5000);
Enter fullscreen mode Exit fullscreen mode

Copy either of the snippets into the Chrome DevTools console panel and run it. Then you have 5 seconds to select and copy something before it appears in the console when the timeout expires.

MDN: Clipboard.readText() - Example

Collapse
 
dev_hills profile image
Hillary Chibuko

yea this is awesome content...
The navigator.clipboard.readText returns a promise ....
so listening for a promise and pasting into the console after five seconds is great , because by then the promise most have resolved...
Kudos!!!

Collapse
 
dev_hills profile image
Hillary Chibuko

peerreynders posted an awesome content about this issue ,I advice you reference it below