Copy to Clipboard Using JavaScript in iOS

Copy to clipboard using Javascript in iOS

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:

  1. Text can only be copied from <input> and <textarea> elements.
  2. If the element holding the text is not inside a <form>, then it must be contenteditable.
  3. The element holding the text must not be readonly (though you may try, this is not an "official" method documented anywhere).
  4. The text inside the element must be in selection range.

To cover all four of these "requirements", you will have to:

  1. Put the text to be copied inside an <input> or <textarea> element.
  2. Save the old values of contenteditable and readonly of the element to be able to restore them after copying.
  3. Change contenteditable to true and readonly to false.
  4. Create a range to select the desired element and add it to the window's selection.
  5. Set the selection range for the entire element.
  6. Restore the previous contenteditable and readonly values.
  7. 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.

Make clipboard copy-paste work on iphone devices

Try this. Works for me.

var copy = function(elementId) {

var input = document.getElementById(elementId);

var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);

if (isiOSDevice) {



var editable = input.contentEditable;

var readOnly = input.readOnly;

input.contentEditable = true;

input.readOnly = false;

var range = document.createRange();

range.selectNodeContents(input);

var selection = window.getSelection();

selection.removeAllRanges();

selection.addRange(range);

input.setSelectionRange(0, 999999);

input.contentEditable = editable;

input.readOnly = readOnly;

} else {

input.select();

}

document.execCommand('copy');

}
<input type="text" id="foo" value="text to copy" />

<button onclick="copy('foo')">Copy text</button>

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>

Keyboard triggering after executing document.execCommand( copy ) in iOS webview mobile device

Copy to clipboard using Javascript in iOS
This one helped me out mitrooooon.



Related Topics



Leave a reply



Submit