JS Copy to Clipboard Discontiguous section - javascript

I have the following JS code for copying to clipboard:
function copyAll(copyEl){
var textToCopy = $(copyEl)[0];
var range = document.createRange();
range.selectNode(textToCopy);
window.getSelection().addRange(range);
try {
// Now that text is selected, execute the copy command
var copyRet = document.execCommand('copy');
var msg = copyRet ? 'successful' : 'unsuccessful';
$('#copyResult').stop(true, true).fadeOut(0).html('Copied to clipboard').fadeIn(500).fadeOut(3000);
// Remove the selections
window.getSelection().removeAllRanges();
console.log('Copy command was ' + msg);
}
catch(err) {
$('#copyResult').stop(true, true).fadeOut(0).html('Oops, unable to copy').fadeIn(500).fadeOut(3000);
console.log('Oops, unable to copy');
}
}
When this function is executed, I get this error and log in the console:
Discontiguous selection is not supported.
Copy command was successful
at this line:
window.getSelection().addRange(range);
And the text is not copied.
So, how come I get an error, still I get Copy command was successful?
Also, this behaviour is not observed always. Sometimes, I do not get this error, and at some other times, I get this error but still the text is copied to clipboard.
I am working only on Chrome.

Looks like it was a bug on Chrome's side. Check if it works properly now. More details here.

The reason that this error is thrown is because of the Selection Object's rangeCount is not zero.
As #dropout has mentioned the Chrome bug, it will avoid addRange to Selection Object if it already has selection range.
And the message 'Copy command was successful' is received because of the non null selection range. So whatever was under selection was added.
To solve this, you should check for the rangeCount. And if rangeCount is not 0, you can fire window.getSelection().empty() or window.getSelection().removeAllRanges(), then only addRange and go for the copy command.
function copyAll(copyEl){
var textToCopy = $(copyEl)[0];
var range = document.createRange();
if(range.rangeCount > 0){
range.removeAllRanges();
}
range.selectNode(textToCopy);
window.getSelection().addRange(range);
try {
// Now that text is selected, execute the copy command
var copyRet = document.execCommand('copy');
var msg = copyRet ? 'successful' : 'unsuccessful';
$('#copyResult').stop(true, true).fadeOut(0).html('Copied to clipboard').fadeIn(500).fadeOut(3000);
// Remove the selections
window.getSelection().removeAllRanges();
console.log('Copy command was ' + msg);
}
catch(err) {
$('#copyResult').stop(true, true).fadeOut(0).html('Oops, unable to copy').fadeIn(500).fadeOut(3000);
console.log('Oops, unable to copy');
}
}

Related

HTML - JavaScript get copy to clipboard?

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.

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>

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.

Copy to clipboard using Javascript in iOS

I'm using this function to copy a URL to the clipboard:
function CopyUrl($this){
var querySelector = $this.next().attr("id");
var emailLink = document.querySelector("#"+querySelector);
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy', false, null);
var msg = successful ? 'successful' : 'unsuccessful';
if(true){
$this.addClass("copied").html("Copied");
}
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
}
Everything works fine on desktop browsers, but not on iOS devices, where my function returns successfully, but the data isn't copied to the clipboard at all. What's causing this and how could I solve this problem?
Update! iOS >= 10
Looks like with the help of selection ranges and some little hack it is possible to directly copy to the clipboard on iOS (>= 10) Safari. I personally tested this on iPhone 5C iOS 10.3.3 and iPhone 8 iOS 11.1. However, there seem to be some restrictions, which are:
Text can only be copied from <input> and <textarea> elements.
If the element holding the text is not inside a <form>, then it must be contenteditable.
The element holding the text must not be readonly (though you may try, this is not an "official" method documented anywhere).
The text inside the element must be in selection range.
To cover all four of these "requirements", you will have to:
Put the text to be copied inside an <input> or <textarea> element.
Save the old values of contenteditable and readonly of the element to be able to restore them after copying.
Change contenteditable to true and readonly to false.
Create a range to select the desired element and add it to the window's selection.
Set the selection range for the entire element.
Restore the previous contenteditable and readonly values.
Run execCommand('copy').
This will cause the caret of the user's device to move and select all the text in the element you want, and then automatically issue the copy command. The user will see the text being selected and the tool-tip with the options select/copy/paste will be shown.
Now, this looks a little bit complicated and too much of an hassle to just issue a copy command, so I'm not sure this was an intended design choice by Apple, but who knows... in the mean time, this currently works on iOS >= 10.
With this said, polyfills like this one could be used to simplify this action and make it cross-browser compatible (thanks #Toskan for the link in the comments).
Working example
To summarize, the code you'll need looks like this:
function iosCopyToClipboard(el) {
var oldContentEditable = el.contentEditable,
oldReadOnly = el.readOnly,
range = document.createRange();
el.contentEditable = true;
el.readOnly = false;
range.selectNodeContents(el);
var s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 999999); // A big number, to cover anything that could be inside the element.
el.contentEditable = oldContentEditable;
el.readOnly = oldReadOnly;
document.execCommand('copy');
}
Note that the el parameter to this function must be an <input> or a <textarea>.
Old answer: previous iOS versions
On iOS < 10 there are some restrictions for Safari (which actually are security measures) to the Clipboard API:
It fires copy events only on a valid selection and cut and paste only in focused editable fields.
It only supports OS clipboard reading/writing via shortcut keys, not through document.execCommand(). Note that "shorcut key" means some clickable (e.g. copy/paste action menu or custom iOS keyboard shortcut) or physical key (e.g. connected bluetooth keyboard).
It doesn't support the ClipboardEvent constructor.
So (at least as of now) it's not possible to programmatically copy some text/value in the clipboard on an iOS device using Javascript. Only the user can decide whether to copy something.
It is however possible to select something programmatically, so that the user only has to hit the "Copy" tool-tip shown on the selection. This can be achieved with the exact same code as above, just removing the execCommand('copy'), which is indeed not going to work.
I've searched for some solutions and I've found one that actually works: http://www.seabreezecomputers.com/tips/copy2clipboard.htm
Basically, example could be something like:
var $input = $(' some input/textarea ');
$input.val(result);
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
var el = $input.get(0);
var editable = el.contentEditable;
var readOnly = el.readOnly;
el.contentEditable = 'true';
el.readOnly = 'false';
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.setSelectionRange(0, 999999);
el.contentEditable = editable;
el.readOnly = readOnly;
} else {
$input.select();
}
document.execCommand('copy');
$input.blur();
This is my cross browser implementation (including iOS)
You can test it by running the snippet below
Example:
copyToClipboard("Hello World");
/**
* Copy a string to clipboard
* #param {String} string The string to be copied to clipboard
* #return {Boolean} returns a boolean correspondent to the success of the copy operation.
* #see https://stackoverflow.com/a/53951634/938822
*/
function copyToClipboard(string) {
let textarea;
let result;
try {
textarea = document.createElement('textarea');
textarea.setAttribute('readonly', true);
textarea.setAttribute('contenteditable', true);
textarea.style.position = 'fixed'; // prevent scroll from jumping to the bottom when focus is set.
textarea.value = string;
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, textarea.value.length);
result = document.execCommand('copy');
} catch (err) {
console.error(err);
result = null;
} finally {
document.body.removeChild(textarea);
}
// manual copy fallback using prompt
if (!result) {
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const copyHotkey = isMac ? '⌘C' : 'CTRL+C';
result = prompt(`Press ${copyHotkey}`, string); // eslint-disable-line no-alert
if (!result) {
return false;
}
}
return true;
}
Demo: <button onclick="copyToClipboard('It works!\nYou can upvote my answer now :)') ? this.innerText='Copied!': this.innerText='Sorry :(' ">Click here</button>
<p>
<textarea placeholder="(Testing area) Paste here..." cols="80" rows="4"></textarea>
</p>
NOTE: It doesn't work when it is not initiated by the user, like timeouts or any async event!
It must come from a trusted event like called from a click event on a button
Problem: iOS Safari only allows document.execCommand('copy') for text within a contentEditable container.
Solution: detect iOS Safari and quickly toggle contentEditable before executing document.execCommand('copy').
The function below works in all browsers. Call with a CSS Selector or HTMLElement:
function copyToClipboard(el) {
// resolve the element
el = (typeof el === 'string') ? document.querySelector(el) : el;
// handle iOS as a special case
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
// save current contentEditable/readOnly status
var editable = el.contentEditable;
var readOnly = el.readOnly;
// convert to editable with readonly to stop iOS keyboard opening
el.contentEditable = true;
el.readOnly = true;
// create a selectable range
var range = document.createRange();
range.selectNodeContents(el);
// select the range
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
el.setSelectionRange(0, 999999);
// restore contentEditable/readOnly to original state
el.contentEditable = editable;
el.readOnly = readOnly;
}
else {
el.select();
}
// execute copy command
document.execCommand('copy');
}
input { font-size: 14px; font-family: tahoma; }
button { font-size: 14px; font-family: tahoma; }
<input class="important-message" type="text" value="Hello World" />
<button onclick="copyToClipboard('.important-message')">Copy</button>
Please check my solution.
It works on Safari (tested on iPhone 7 and iPad) and on other browsers.
window.Clipboard = (function(window, document, navigator) {
var textArea,
copy;
function isOS() {
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range,
selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyToClipboard() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};
return {
copy: copy
};
})(window, document, navigator);
// How to use
Clipboard.copy('text to be copied');
https://gist.github.com/rproenca/64781c6a1329b48a455b645d361a9aa3
https://fiddle.jshell.net/k9ejqmqt/1/
Hope that helps you.
Regards.
My solution was created by combining others answers from this page.
Unlike the other answers, it does not require that you already have an element on the page. It will create its own textarea, and clean up the mess afterwards.
function copyToClipboard(str) {
var el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
// save current contentEditable/readOnly status
var editable = el.contentEditable;
var readOnly = el.readOnly;
// convert to editable with readonly to stop iOS keyboard opening
el.contentEditable = true;
el.readOnly = true;
// create a selectable range
var range = document.createRange();
range.selectNodeContents(el);
// select the range
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
el.setSelectionRange(0, 999999);
// restore contentEditable/readOnly to original state
el.contentEditable = editable;
el.readOnly = readOnly;
} else {
el.select();
}
document.execCommand('copy');
document.body.removeChild(el);
}
iOS 13.4 and newer
As of version 13.4, iOS Safari supports the modern async clipboard API:
MDN: Clipboard API
Can I Use: clipboard.writeText
Like with everything in JavaScript, the newer API is about 1000x nicer but you still need gross fallback code, since a bunch of your users will be on old versions for some years.
Here's how to use the new clipboard API with the code in the original question:
function CopyUrl($this){
var querySelector = $this.next().attr("id");
var emailLink = document.querySelector("#"+querySelector);
if (navigator.clipboard) {
var myText = emailLink.textContent;
navigator.clipboard.writeText(myText).then(function() {
// Do something to indicate the copy succeeded
}).catch(function() {
// Do something to indicate the copy failed
});
} else {
// Here's where you put the fallback code for older browsers.
}
}
Clipboard API was added in Safari 13.1, see here https://webkit.org/blog/10247/new-webkit-features-in-safari-13-1/
It's now as simple as navigator.clipboard.writeText("Text to copy")
nice one, here's the typescript refactor of above in case anyone is interested (written as ES6 module):
type EditableInput = HTMLTextAreaElement | HTMLInputElement;
const selectText = (editableEl: EditableInput, selectionStart: number, selectionEnd: number) => {
const isIOS = navigator.userAgent.match(/ipad|ipod|iphone/i);
if (isIOS) {
const range = document.createRange();
range.selectNodeContents(editableEl);
const selection = window.getSelection(); // current text selection
selection.removeAllRanges();
selection.addRange(range);
editableEl.setSelectionRange(selectionStart, selectionEnd);
} else {
editableEl.select();
}
};
const copyToClipboard = (value: string): void => {
const el = document.createElement('textarea'); // temporary element
el.value = value;
el.style.position = 'absolute';
el.style.left = '-9999px';
el.readOnly = true; // avoid iOs keyboard opening
el.contentEditable = 'true';
document.body.appendChild(el);
selectText(el, 0, value.length);
document.execCommand('copy');
document.body.removeChild(el);
};
export { copyToClipboard };
This one worked for me for a readonly input element.
copyText = input => {
const isIOSDevice = navigator.userAgent.match(/ipad|iphone/i);
if (isIOSDevice) {
input.setSelectionRange(0, input.value.length);
} else {
input.select();
}
document.execCommand('copy');
};
My function for ios and other browsers copying to clipboard after tested on ios: 5c,6,7
/**
* Copies to Clipboard value
* #param {String} valueForClipboard value to be copied
* #param {Boolean} isIOS is current browser is Ios (Mobile Safari)
* #return {boolean} shows if copy has been successful
*/
const copyToClipboard = (valueForClipboard, isIOS) => {
const textArea = document.createElement('textarea');
textArea.value = valueForClipboard;
textArea.style.position = 'absolute';
textArea.style.left = '-9999px'; // to make it invisible and out of the reach
textArea.setAttribute('readonly', ''); // without it, the native keyboard will pop up (so we show it is only for reading)
document.body.appendChild(textArea);
if (isIOS) {
const range = document.createRange();
range.selectNodeContents(textArea);
const selection = window.getSelection();
selection.removeAllRanges(); // remove previously selected ranges
selection.addRange(range);
textArea.setSelectionRange(0, valueForClipboard.length); // this line makes the selection in iOS
} else {
textArea.select(); // this line is for all other browsers except ios
}
try {
return document.execCommand('copy'); // if copy is successful, function returns true
} catch (e) {
return false; // return false to show that copy unsuccessful
} finally {
document.body.removeChild(textArea); // delete textarea from DOM
}
};
above answer about contenteditable=true. I think only belongs to divs. And for <textarea> is not applicable.
isIOS variable can be checked as
const isIOS = navigator.userAgent.match(/ipad|ipod|iphone/i);
Update: Looks like with latest browsers you can now use the Clipboard API:
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
Using navigator.clipboard.writeText('MyText') will write any String you need in the clipboard, no need for inputs, document.execCommand('copy') etc...
This improves Marco's answer by allowing the text to be passed as a variable.
This works on ios >10.
This does not work on Windows.
function CopyToClipboardIOS(TheText) {
var el=document.createElement('input');
el.setAttribute('style','position:absolute;top:-9999px');
el.value=TheText;
document.body.appendChild(el);
var range = document.createRange();
el.contentEditable=true;
el.readOnly = false;
range.selectNodeContents(el);
var s=window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 999999);
document.execCommand('copy');
el.remove();
}
<input id="copyIos" type="hidden" value="">
var clipboard = new Clipboard('.copyUrl');
//兼容ios复制
$('.copyUrl').on('click',function() {
var $input = $('#copyIos');
$input.val(share_url);
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
clipboard.on('success', function(e) {
e.clearSelection();
$.sDialog({
skin: "red",
content: 'copy success!',
okBtn: false,
cancelBtn: false,
lock: true
});
console.log('copy success!');
});
} else {
$input.select();
}
//document.execCommand('copy');
$input.blur();
});

How to force update HTML's TextArea element?

Sorry for newbie question but it's related to WebKit issue. I have the next JS code:
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
console.log('updated element.value');
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})
element is textarea element:
<textarea id="output" rows="8"></textarea>
I have code that printf using that function and then shows prompt to type user name.
So i expect to see 'updated element.value' in browser console and printed text in textarea before prompt dialog is shown.
How can i force textarea to refresh after it's changed (element.value += text + "\n")?
It works as expected in chrome/firefox but fails in Safari(WebKit) - i can't see output at the moment prompt dialog is shown.
To me it sounds like something that can't be done, but there might be Webkit specific hacks I'm not aware about. Maybe all browsers do both updates during the same render cycle which you'd expect, but Safari displays the prompt first and somehow pauses the remaining updates until the prompt is dismissed.
The most obvious workaround is something like
print('lorem ipsum');
setTimeout(function(){
var response = prompt('my question here');
//handle the response
}, 10);
which is likely to guarantee that the textarea update happens before the prompt locks things.

Categories

Resources