How to Copy to the Clipboard in JavaScript

How do I copy to the clipboard in JavaScript?

Overview

There are three primary browser APIs for copying to the clipboard:

  1. Async Clipboard API [navigator.clipboard.writeText]

    • Text-focused portion available in Chrome 66 (March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
  2. document.execCommand('copy') (deprecated) /p>

    • Most browsers support this as of ~April 2015 (see Browser Support below).
    • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
    • Text is read from the DOM and placed on the clipboard.
    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
  3. Overriding the copy event

    • See Clipboard API documentation on Overriding the copy event.
    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
    • Not covered here as it doesn't directly answer the question.

General development notes

Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.

IMPORTANT (noted here 2020/02/20)

Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).

To develop create your own web page, serve that page over an HTTPS connection to test and develop against.

Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/

Async + Fallback

Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.

Here is a simple example (may not work embedded in this site, read "important" note above):

function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;

// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}

document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

</textarea>
</div>

How do I copy to the clipboard in JavaScript?

Overview

There are three primary browser APIs for copying to the clipboard:

  1. Async Clipboard API [navigator.clipboard.writeText]

    • Text-focused portion available in Chrome 66 (March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
  2. document.execCommand('copy') (deprecated) /p>

    • Most browsers support this as of ~April 2015 (see Browser Support below).
    • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
    • Text is read from the DOM and placed on the clipboard.
    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
  3. Overriding the copy event

    • See Clipboard API documentation on Overriding the copy event.
    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
    • Not covered here as it doesn't directly answer the question.

General development notes

Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.

IMPORTANT (noted here 2020/02/20)

Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).

To develop create your own web page, serve that page over an HTTPS connection to test and develop against.

Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/

Async + Fallback

Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.

Here is a simple example (may not work embedded in this site, read "important" note above):

function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;

// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}

document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

</textarea>
</div>

Copy text of a specific tag to clipboard using JavaScript

function copy_text_fun() {
//getting text from P tag
var copyText = document.getElementById("copy_txt");
// creating textarea of html
var input = document.createElement("textarea");
//adding p tag text to textarea
input.value = copyText.textContent;
document.body.appendChild(input);
input.select();
document.execCommand("Copy");
// removing textarea after copy
input.remove();
alert(input.value);
}
<p id="copy_txt">hi</p>
<button onclick="copy_text_fun()">Copy</button>

Copy output of a JavaScript variable to the clipboard

OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.

So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.

JavaScript function:

function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
checkbx.toString();

// Create a dummy input to copy the string array inside it
var dummy = document.createElement("input");

// Add it to the document
document.body.appendChild(dummy);

// Set its ID
dummy.setAttribute("id", "dummy_id");

// Output the array into it
document.getElementById("dummy_id").value=checkbx;

// Select it
dummy.select();

// Copy its contents
document.execCommand("copy");

// Remove it as its not needed anymore
document.body.removeChild(dummy);
}

And its HTML call:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>

Copy to clipboard in chrome extension V3

I'll follow the excellent suggestion wOxxOm gave you, elaborating it in a concrete example. What you want to do is have a ContentScript.js that runs on any active tab with a web page, since you can't access the DOM from the backGround.js, and then send a message to this script, from where you would copy to the clipboard.

manifest.json

    "background" :{
"service_worker" :"eventPage.js"
},
"permissions" : [
"contextMenus",
"clipboardWrite"
],
"content_scripts": [ // this is what you need to add
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],

From the background.js, you would send a message, that will be handled in the ContentScript.js

background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id,
{
message: "copyText",
textToCopy: "some text"
}, function(response) {})
})

In the contentScript.js, you would catch the message and copy it to the clipboard.

content.js

chrome.runtime.onMessage.addListener( // this is the message listener
function(request, sender, sendResponse) {
if (request.message === "copyText")
copyToTheClipboard(request.textToCopy);
}
);

async function copyToTheClipboard(textToCopy){
const el = document.createElement('textarea');
el.value = textToCopy;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}

Javascrypt copy to clipboard function copying just first row

first, you need remove id property ("key") from your input text, because there should be no duplicate ids on a document.

Then you can change your js, taking the input ("key") element by its sibling to current clicked button.

 function myFunction(el) {
var hidden = el.previousElementSibling;
hidden.style.display = 'block';
hidden.select();
hidden.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied the text: " + hidden.value);
hidden.style.display = 'none';
}
 <table>
<tr>
<td class="ttd"> </td>
<td class="ttd">1</td>
<td class="ttd">2</td>
<td class="ttd">3</td>
<td class="ttd">4</td>
<td class="ttd">5</td>
<td class="ttd">6</td>
<td class="ttd">7</td>
<td class="ttd">
<input type="text" style="display:none;" value="12321">
<button onclick="myFunction(this)" >Copy</button>
</td>
</tr>
<tr>
<td class="ttd"> </td>
<td class="ttd">1</td>
<td class="ttd">2</td>
<td class="ttd">3</td>
<td class="ttd">4</td>
<td class="ttd">5</td>
<td class="ttd">6</td>
<td class="ttd">7</td>
<td class="ttd">
<input type="text" style="display:none;" value="2222">
<button onclick="myFunction(this)" >Copy</button>
</td>
</tr>
</table>

copy to clipboard in JavaScript from row data

select() is a method of HTMLInputElement. Currently, copyText is a string. To use copy command, you need to create dummy input in Html.

function copyPaste(number) {
var dummy = document.createElement("input");

// Add it to the document
document.body.appendChild(dummy);

// Set value of input
dummy.value = number;

/* Select the text field */
dummy.select();
dummy.setSelectionRange(0, 99999); /* For mobile devices */

/* Copy the text inside the text field */
document.execCommand("copy");

// Remove it as its not needed anymore
document.body.removeChild(dummy);

/* Alert the copied text */
alert("Copied the text: " + number);
}

How do I copy to the clipboard in JavaScript?

Overview

There are three primary browser APIs for copying to the clipboard:

  1. Async Clipboard API [navigator.clipboard.writeText]

    • Text-focused portion available in Chrome 66 (March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
  2. document.execCommand('copy') (deprecated) /p>

    • Most browsers support this as of ~April 2015 (see Browser Support below).
    • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
    • Text is read from the DOM and placed on the clipboard.
    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
  3. Overriding the copy event

    • See Clipboard API documentation on Overriding the copy event.
    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
    • Not covered here as it doesn't directly answer the question.

General development notes

Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.

IMPORTANT (noted here 2020/02/20)

Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).

To develop create your own web page, serve that page over an HTTPS connection to test and develop against.

Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/

Async + Fallback

Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.

Here is a simple example (may not work embedded in this site, read "important" note above):

function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;

// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}

document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

</textarea>
</div>


Related Topics



Leave a reply



Submit