Reputation: 3538
I'm trying to scrape some data off a page and can't quite get document.execCommand("copy")
to work as expected.
As a test, I am injecting some HTML into the page and then try to copy it to the clipboard
$('#topcard h1').append('<a id="getData" type="text">This is some data</a>')
I can then see This is some data
on the page appear
Then:
var copyText = document.querySelector("#getData")
copyText
Shows in the console:
<a id="getData" type="text">This is some data</a>
It seems that copyText
is exactly what I want it to be.
However:
copyText.select()
returns
VM2319:1 Uncaught TypeError: copyText.select is not a function
at <anonymous>:1:10
What am I doing wrong?
Upvotes: 0
Views: 189
Reputation: 21495
.select()
will let you set the selection range for an <input>
or <textarea>
:
document.getElementById("foo").select()
<input id="foo" value="12345">
...but will not work for other DOM nodes (including contentEditable nodes). To select anything other than a form field's contents, you need to use the Selection API:
var r = document.createRange();
r.selectNode(document.getElementById("foo"));
var s = window.getSelection();
s.addRange(r);
<div id="foo">12345</div>
In either case, once the selection is made you can then use document.execCommand("copy")
to capture the selected text to the clipboard -- but with one very important caveat: this must be done within a user-initiated event handler. (This is to prevent malicious websites from hijacking the user's clipboard without their knowledge.)
var captureSelection = function() {
var r = document.createRange();
r.selectNode(document.getElementById("foo"));
var s = window.getSelection();
s.addRange(r);
document.execCommand("copy");
}
// this will select the DOM node, but will not copy it to
// the clipboard (because it's not user-initiated):
captureSelection();
// this _will_ copy it to the clipboard:
document.getElementById("bar").onclick = captureSelection;
<div id="foo">12345</div>
<button id="bar">Go</button>
<br><br>
<textarea placeholder="paste text here"></textarea>
Upvotes: 1