Nino Amisulashvili Nino Amisulashvili - 1 year ago 332
iOS Question

Copy to clipboard using Javascript in iOS

I'm using this function to copy a URL to the clipboard:

function CopyUrl($this){

var querySelector = $"id");
var emailLink = document.querySelector("#"+querySelector);

var range = document.createRange();

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';


} catch(err) {
console.log('Oops, unable to copy');

// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported

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?

Answer Source

There's no problem with your code. However on iOS Safari there are some restrictions (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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download