Eric Bergman-Terrell's Blog

Javascript / HTML Tip: How to Programmatically Copy Text from a Web Page to the Clipboard
October 7, 2015

I recently updated my Base64 Decoder/Encoder, JSON Pretty Print and XML Pretty Print utilities by adding a button that copies the text to the clipboard. The technique I used is to select the field containing the text, and then call document.execCommand('copy') to copy the field's text into the clipboard. The following code snippet first selects the <TEXTAREA> with an id of "Text", and then copies its text to the clipboard. It uses jQuery for the necessary client-side HTML manipulation.

Note, document.execCommand('copy') doesn't work on every browser, but I've verified that it works on Firefox, IE, and Chrome on the desktop, and on the Chrome browser on Android. That's why the call is inside of a try / catch block.

$(document).ready(function () {
    $('#copy').click(function() {

        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('unable to copy: ' + err);

no-one can copy these good looks
No-one can copy my good looks!

Keywords: Javascript, jQuery, clipboard, document.execCommand('copy'), browser support, HTML

Reader Comments

Comment on this Blog Post

Recent Posts

Python Script to Audit MediaMonkey TranscodingAugust 15, 2019
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015