Have you heard about Envirotechnical? Let's fight climate change one byte at a time :) Learn More →

logo
Published on

How to copy paste with Javascript, an easy guide

Authors
Table of Contents

How to copy paste in Javascript

We are all Stackoverflow heroes until the very moment we need to implement our own copy-paste solution with Javascript.

Many of you asked me how this problem could be solved and I took it upon me to write a blog post to show you how to develop a copy paste snippet with Javascript.

Now, I can already see the drops of sweat coming down your forehead and it's kind of disgusting (that's a joke, just in case you're easily offended) so I will just tell you what a Clipboard is and how we can achieve really great results using it with Javascript.

Javascript copy to clipboard

The Clipboard is a Javascript interface that has a method with which we can implement our copy-paste Javascript solution.

There are two methods to this Interface:

const pasted = navigator.clipboard.writeText('This is some text copy-pasted from your web app')

const readText = navigator.clipboard.readText(
  'This is some text that was previously copy-pasted from your web app'
)

The Javascript Clipboard API permissions are automatically granted upon visiting the tab (active tab) that you want to copy-paste from.

Javascript code for copy-pasting content

const veryImportantPoetry = `
    Never gonna give you up
    Never gonna let you down
    Never gonna run around and desert you
    Never gonna make you cry
    Never gonna say goodbye
    Never gonna tell a lie and hurt you
`

navigator.clipboard.writeText(veryImportantPoetry).then(function () {
  // Do whatever you want with your copy-pasted text
})

Now that you've seen how simple copy-pasting code is with Javascript, go and implement it in your own web application and share the link with me by writing on this discussion!

The goodbye

I hope you found this article useful and to your liking and if you have any requests, drop a message on one of my social media accounts or open an issue/start a discussion on github, on this repository!