HTML - JavaScript get copy to clipboard? - javascript

document.getElementById("x").innerHTML = PosX;
document.getElementById("y").innerHTML = PosY;
<p><span id="x"></span>,<span id="y"></span></p>
How can I get copy to clipboard. This <p> value?
Could you help me? Thanks..
navigator.clipboard.writeText(copyText.value);
I read almost all post about it. And, I just found this code. However, I didn't understand how can I use it.

To do this, you need to first select the <p> element and get its value. For example:
let copyText = document.querySelector("p").innerText;
navigator.clipboard.writeText(copyText).then(() => {
console.log("Copied to clipboard!");
}).catch(error => {
console.error("Failed to copy: ", error);
});
In this example, document.querySelector("p") selects the first <p> element on the page, and innerText gets its text content. Then, the writeText method is used to copy the text to the clipboard, and the .then and .catch methods are used to handle success and error cases, respectively.

You can add a button that when clicked, will copy the text in the element to the clipboard. Here's an example:
<p><span id="x"></span>,<span id="y"></span></p>
<button id="copy-btn">Copy to Clipboard</button>
<script>
document.getElementById("x").innerHTML = PosX;
document.getElementById("y").innerHTML = PosY;
let copyBtn = document.getElementById("copy-btn");
copyBtn.addEventListener("click", function() {
let copyText = document.querySelector("p");
navigator.clipboard.writeText(copyText.innerText).then(function() {
console.log("Copied to clipboard");
}, function(err) {
console.error("Could not copy text: ", err);
});
});
</script>
When the user clicks the "Copy to Clipboard" button, the text in the element will be copied to the clipboard.

Related

Copy text to clipboard. Template literal [duplicate]

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.
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);
}
return checkbx;
}
And to call it I use:
<button id="btn_test" type="button" >Check</button>
<script>
document.getElementById('btn_test').onclick = function() {
var checkedBoxes = getSelectedCheckboxes("my_id");
alert(checkedBoxes);
}
</script>
Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:
checkbx = document.execCommand("copy");
or
checkbx.execCommand("copy");
at the end of the function and then calling it like:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
But it does not work. No data is copied to clipboard.
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// to avoid breaking orgain page when copying more words
// cant copy when adding below this code
// dummy.style.display = 'none'
document.body.appendChild(dummy);
//Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
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>
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Very useful. I modified it to copy a JavaScript variable value to clipboard:
function copyToClipboard(val){
var dummy = document.createElement("input");
dummy.style.display = 'none';
document.body.appendChild(dummy);
dummy.setAttribute("id", "dummy_id");
document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject
I managed to copy text to the clipboard (without showing any text boxes) by adding a hidden input element to body, i.e.:
function copy(txt){
var cb = document.getElementById("cb");
cb.value = txt;
cb.style.display='block';
cb.select();
document.execCommand('copy');
cb.style.display='none';
}
<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>
Use Clipboard API
text = "HEllo World";
navigator.clipboard.writeText(text)
It works on Chrome 66+, Edge 79+, Firefox 63+ & doesn't work on I.E.
Read More About Clipboard API At MDN Docs
Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.
IE11 has its own API.
And the workaround in the accepted answer can be used for unsecure hosts.
function copyToClipboard (text) {
if (navigator.clipboard) { // default: modern asynchronous API
return navigator.clipboard.writeText(text);
} else if (window.clipboardData && window.clipboardData.setData) { // for IE11
window.clipboardData.setData('Text', text);
return Promise.resolve();
} else {
// workaround: create dummy input
const input = h('input', { type: 'text' });
input.value = text;
document.body.append(input);
input.focus();
input.select();
document.execCommand('copy');
input.remove();
return Promise.resolve();
}
}
Note: it uses Hyperscript to create the input element (but should be easy to adapt)
There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.
At the time of writing, setting display:none on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px in width for this to work.
The following example worked in Chrome and Firefox:
const str = 'Copy me';
const el = document.createElement("input");
// Does not work:
// dummy.style.display = "none";
el.style.height = '0px';
// Does not work:
// el.style.width = '0px';
el.style.width = '1px';
document.body.appendChild(el);
el.value = str;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.
I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.
Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.
function doCopy() {
try{
var unique = document.querySelectorAll('.unique');
var msg ="";
unique.forEach(function (unique) {
msg+=unique.value;
});
var temp =document.createElement("textarea");
var tempMsg = document.createTextNode(msg);
temp.appendChild(tempMsg);
document.body.appendChild(temp);
temp.select();
document.execCommand("copy");
document.body.removeChild(temp);
console.log("Success!")
}
catch(err) {
console.log("There was an error copying");
}
}
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>
<input type="text" class="unique" size="18" value="">
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
function CopyText(toCopy, message) {
var body = $(window.document.body);
var textarea = $('<textarea/>');
textarea.css({
position: 'fixed',
opacity: '0'
});
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful)
throw successful;
else
alert(message);
} catch (err) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
}
textarea.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<button type="button" onClick="CopyText('Hello World', 'Text copped!!')">Copy</button>

Javascript - Copy to clipboard without concrete Id in HTML tag

On an HTML page, there should be several snippets in code tags. It should be possible to copy the code to the clipboard via a button click. I have working code for one code tag for which the reference is made using an ID. However, how to change the JavaScript code so that the copying is not dependent on a manually predefined ID in the code tag. When hitting the copy to clipboard button for a certain code snippet, it should automatically copy the content of the intended code block - while having many other code tags with the same copy to clipboard button on the page. My example shows one code block with a predefined ID. How to avoid the ID in the JS code to make it work independently?
function copy_text() {
const str = document.getElementById("copy_code").innerText; const el = document.createElement("textarea");
el.value = str; el.setAttribute("readonly", ""); el.style.position = "absolute";
el.style.left = '-9999px'; document.body.appendChild(el);
el.select(); document.execCommand("copy"); document.body.removeChild(el);
};
<code id="copy_code">some code 1<br>some code 2<br>some code 3</code>
<button onclick="copy_text()">Copy to clipboard</button>
You can pass this to the copy_text() method call so your function knows exactly which button triggered the onclick event. You can then get the elements of it's parent container, assuming each code block and it's button are inside inside a parent container:
function copy_text(item) {
const str = item.parentNode.querySelector('code').innerText;
const el = document.createElement("textarea");
el.value = str;
el.setAttribute("readonly", "");
el.style.position = "absolute";
el.style.left = '-9999px';
document.body.appendChild(el);
el.select(); document.execCommand("copy");
document.body.removeChild(el);
};
<div>
<code>1<br>2<br>3</code>
<button onclick="copy_text(this)">copy</button>
</div>
<div>
<code>4<br>5<br>6</code>
<button onclick="copy_text(this)">copy</button>
</div>
In case if each code block and it's button are not inside some parent container and are entered in HTML exactly like in the question you can use
const str = item.previousElementSibling.innerText;
instead of
const str = item.parentNode.querySelector('code').innerText;
function copy_text(item) {
const str = item.previousElementSibling.innerText;
const el = document.createElement("textarea");
el.value = str;
el.setAttribute("readonly", "");
el.style.position = "absolute";
el.style.left = '-9999px';
document.body.appendChild(el);
el.select(); document.execCommand("copy");
document.body.removeChild(el);
};
<code>1<br>2<br>3</code>
<button onclick="copy_text(this)">copy</button>
<br>
<code>4<br>5<br>6</code>
<button onclick="copy_text(this)">copy</button>
Please note that document.execCommand is being superseded by the clipboard API.
Just pass the id of the element it's supposed to work on to the copy handler. This keeps it independent of the DOM structure and the way that the button and the corresponding code block are placed in the DOM, relative to each other.
function copy_text(id) {
if (!id) return;
const code = document.getElementById(id);
if (!code) return;
if (navigator && navigator.clipboard) { // need to check because it's only available on https and localohost
navigator.clipboard.writeText(code.innerHTML);
}
};
<code id="foo">some code 1<br>some code 2<br>some code 3</code>
<button onclick="copy_text('foo')">Copy to clipboard</button>
<br/>
<code id="bar">some code 3<br>some code 4<br>some code 5</code>
<button onclick="copy_text('bar')">Copy to clipboard</button>
<textarea placeholder="Try to paste here to see if it works"></textarea>
If the DOM structure is fix anyway (the code block always directly being followed by the copy button), you can get rid of the id completely using element.previousElementSibling. In the following example I'm generating the button elements dynamically:
function copy_text(e) {
const code = e.target.previousElementSibling;
if (!code) return;
if (navigator && navigator.clipboard) { // need to check because it's only available on https and localohost
navigator.clipboard.writeText(code.innerHTML);
}
}
document.addEventListener('DOMContentLoaded', function() {
const snippets = document.querySelectorAll('.copyable-snippet');
for (const snippet of snippets) {
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Copy to clipboard';
button.addEventListener('click', copy_text);
snippet.parentElement.insertBefore(button, snippet.nextSibling);
}
});
<code class="copyable-snippet">some code 1<br>some code 2<br>some code 3</code>
<code class="copyable-snippet">some code 3<br>some code 4<br>some code 5</code>
<textarea placeholder="Try to paste here to see if it works"></textarea>

How can `document.execCommand()` copy a special text? [duplicate]

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.
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);
}
return checkbx;
}
And to call it I use:
<button id="btn_test" type="button" >Check</button>
<script>
document.getElementById('btn_test').onclick = function() {
var checkedBoxes = getSelectedCheckboxes("my_id");
alert(checkedBoxes);
}
</script>
Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:
checkbx = document.execCommand("copy");
or
checkbx.execCommand("copy");
at the end of the function and then calling it like:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
But it does not work. No data is copied to clipboard.
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// to avoid breaking orgain page when copying more words
// cant copy when adding below this code
// dummy.style.display = 'none'
document.body.appendChild(dummy);
//Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
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>
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Very useful. I modified it to copy a JavaScript variable value to clipboard:
function copyToClipboard(val){
var dummy = document.createElement("input");
dummy.style.display = 'none';
document.body.appendChild(dummy);
dummy.setAttribute("id", "dummy_id");
document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject
I managed to copy text to the clipboard (without showing any text boxes) by adding a hidden input element to body, i.e.:
function copy(txt){
var cb = document.getElementById("cb");
cb.value = txt;
cb.style.display='block';
cb.select();
document.execCommand('copy');
cb.style.display='none';
}
<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>
Use Clipboard API
text = "HEllo World";
navigator.clipboard.writeText(text)
It works on Chrome 66+, Edge 79+, Firefox 63+ & doesn't work on I.E.
Read More About Clipboard API At MDN Docs
Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.
IE11 has its own API.
And the workaround in the accepted answer can be used for unsecure hosts.
function copyToClipboard (text) {
if (navigator.clipboard) { // default: modern asynchronous API
return navigator.clipboard.writeText(text);
} else if (window.clipboardData && window.clipboardData.setData) { // for IE11
window.clipboardData.setData('Text', text);
return Promise.resolve();
} else {
// workaround: create dummy input
const input = h('input', { type: 'text' });
input.value = text;
document.body.append(input);
input.focus();
input.select();
document.execCommand('copy');
input.remove();
return Promise.resolve();
}
}
Note: it uses Hyperscript to create the input element (but should be easy to adapt)
There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.
At the time of writing, setting display:none on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px in width for this to work.
The following example worked in Chrome and Firefox:
const str = 'Copy me';
const el = document.createElement("input");
// Does not work:
// dummy.style.display = "none";
el.style.height = '0px';
// Does not work:
// el.style.width = '0px';
el.style.width = '1px';
document.body.appendChild(el);
el.value = str;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.
I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.
Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.
function doCopy() {
try{
var unique = document.querySelectorAll('.unique');
var msg ="";
unique.forEach(function (unique) {
msg+=unique.value;
});
var temp =document.createElement("textarea");
var tempMsg = document.createTextNode(msg);
temp.appendChild(tempMsg);
document.body.appendChild(temp);
temp.select();
document.execCommand("copy");
document.body.removeChild(temp);
console.log("Success!")
}
catch(err) {
console.log("There was an error copying");
}
}
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>
<input type="text" class="unique" size="18" value="">
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
function CopyText(toCopy, message) {
var body = $(window.document.body);
var textarea = $('<textarea/>');
textarea.css({
position: 'fixed',
opacity: '0'
});
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful)
throw successful;
else
alert(message);
} catch (err) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
}
textarea.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<button type="button" onClick="CopyText('Hello World', 'Text copped!!')">Copy</button>

Copying to clipboard with document.execCommand('copy') fails with big texts

I'm using a hidden text area to put some text, select it and then using document.execCommand to copy it to the clipboard. This usually works but fails (returns false) when the text is large. In Chrome v55, it seems to fail around 180K characters.
Is there a limit to the amount of data that can be copied this way? Normal Ctrl+C doesn't seem subject to the same limitations.
note: someone marked this as a possible duplicate of Does document.execCommand('copy') have a size limitation?. It might be similar question, but that one was tagged as a specific framework that I don't use and also, it wasn't answered. I believe my question is more general and still relevant.
I attach the code for reference.
function copyTextToClipboard(text) {
var textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
The problem has more to do with the time it takes to render this long text than the execCommand('copy') call itself.
Firefox raises an quite explanatory error message :
document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.
Your code takes too long to generate the text, and thus the browser doesn't recognizes it as an semi-trusted event...
The solution is then to generate this text first, and only after listen to an user-gesture to call execCommand. So to make it possible, you can e.g. listen to a mousedown event to generate the text, and only in the mouseup event will you really execute the copy command.
const text = ('some text a bit repetitive ' + Date.now()).repeat(50000);
function copyTextToClipboard(text) {
// first we create the textArea
var textArea = document.createElement('textarea');
textArea.style.position = 'absolute';
textArea.style.opacity = '0';
textArea.value = text;
document.body.appendChild(textArea);
var execCopy = e => { // triggered on mouseup
textArea.select();
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
document.body.removeChild(textArea);
};
// here the magic
btn.addEventListener('mouseup', execCopy, {
once: true
});
}
// triggered on mousedown
btn.onmousedown = e => copyTextToClipboard(text);
<button id="btn">copy some text in your clipboard</button>
<p>May struggle your browser a little bit, it's quite a long text... Please be patient</p>
I faced similar issue and came up with the workaround described here: How to copy extra large values to clipboard?
Idea is to check the size of the content to be copied to the clipboard and in case of size more than 150k symbols create a text file and throw it to a user.
After 5 years of usage I heard no complaints from end-users.

Write text to Clipboard

I want to write some text variable into clipboard via Chrome Extension, it will be happened when user presses a short-key. I've done all parts except writing to clipboard.
I've searched entire StackOverflow using these keywords:
"[google-chrome-extension] Clipboard"
So I want to say, I've seen all related to:
Add clipboardRead and clipboardWrite permission (already done)
Add text into a <textarea>, call
document.execCommand('Copy');
or
document.execCommand("Copy", false, null);
Even I tried my extension on StackOverflow's textarea and I inserted my text into wmd-input part of StackOverflow textarea, then selected it, then called copy. Nothing, nothing, nothing...
Everything tried. Please advise... What am I missing?
Based on https://stackoverflow.com/a/12693636
function directCopy(str){
//based on https://stackoverflow.com/a/12693636
document.oncopy = function(event) {
event.clipboardData.setData("Text", str);
event.preventDefault();
};
document.execCommand("Copy");
document.oncopy = undefined;
}
You can try the following code, it writes text to clipboard
As an example i wrote Sample to clipboard
Output
manifest.json
manifest file is key for all chrome extensions, ensured it is with all permissions
{
"name": "Copy to ClipBoard Demo",
"description" : "This is used for demonstrating Copy to Clip Board Functionality",
"version": "1",
"browser_action": {
"default_popup": "popup.html"
},
"permissions":["clipboardWrite"],
"manifest_version": 2
}
popup.html
A trivial Browser action HTML File, with input box and button
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<input type="text" id="text" placeHolder="Enter Text To Copy"></input>
<button id="copy">Copy</button>
</body>
</html>
popup.js
It copies content in <input> to clipboard
function copy() {
//Get Input Element
var copyDiv = document.getElementById('text');
//Give the text element focus
copyDiv.focus();
//Select all content
document.execCommand('SelectAll');
//Copy Content
document.execCommand("Copy", false, null);
}
//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("copy").onclick = copy;
});
OR
function copy(){
//Get Input Element
document.getElementById("text").select();
//Copy Content
document.execCommand("Copy", false, null);
}
//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("copy").onclick = copy;
});
Usage example:
copyStringToClipboard("abc123");
function copyStringToClipboard (str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
Suonds like you're trying to copy from a content script. Building off joelpt and Jeff Gran's answers from this answer, here's how to copy any piece of text from a content script:
"permissions": [
"clipboardWrite",...
In your main.js or any background script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
var copyFrom = document.createElement("textarea");
copyFrom.textContent = request.text;
var body = document.getElementsByTagName('body')[0];
body.appendChild(copyFrom);
copyFrom.select();
document.execCommand('copy');
body.removeChild(copyFrom);
})
From your content script:
chrome.runtime.sendMessage({text:textToCopy});

Categories

Resources