DEV Community

How to copy text to the clipboard with Javascript

tq-bit on April 01, 2021

Copying data from the browser into your clipboard is a small feature, yet a quite powerful one. No more manual selecting & crtl + c does save a...
Collapse
 
mariamoalli profile image
Mariam Oluseyi-Alli

thank you for this article, it was very helpful

Collapse
 
devmor profile image
Devmor

Hey thanks this is good. Just found a typo:

const input = el.tagName === 'input' ? ...
Enter fullscreen mode Exit fullscreen mode

'input' should be 'INPUT' because tag names are uppercase.

const input = el.tagName === 'INPUT' ? ...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
off_samuelzin profile image
samuel

Thank you guy I need this.

Collapse
 
tqbit profile image
tq-bit

Glad it helped. Out of curiousity: Did you go for the execCommand or navigator option?

Collapse
 
off_samuelzin profile image
samuel

Navigation option in my vision it's so much better

Collapse
 
jorik profile image
Jorik • Edited

Also worth mentioning Transmat for a third option using the DataTransfer API, this will also include drag-drop! :-)

google.github.io/transmat/

Collapse
 
tqbit profile image
tq-bit • Edited

Cool idea. I've already used DataTransfer for dropping a file in the browser for fileupload, didn't know it works the other way around as well

Collapse
 
sincapshop profile image
Sincap Shop

Method 2: Clipboard API
How can I integrate it into my chrome extension because it doesn't work in the extension while it works in the normal browser.

Let me put it this way, I print a part of the source of a web page to my plugin and I want it to copy when a button is clicked.

Collapse
 
tqbit profile image
tq-bit

I think chrome extensions run in their own sandbox environment. Instead of requesting permission in the browser, you need to 'proxy' them towards the env plugins run within.

There's this section in the docs describing how to do so, I hope it'll help you: developer.chrome.com/docs/extensio...

Collapse
 
aalphaindia profile image
Pawan Pawar

excellent!

Collapse
 
huydzzz profile image
Pơ Híp

you are kind

Collapse
 
burgercousin profile image
Pentium_4

thx!

Collapse
 
diraskreact profile image
Info Comment hidden by post author - thread only accessible via permalink
Dirask-React • Edited

Some comments have been hidden by the post's author - find out more