Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using document.execCommand('copy') in mobile

Is there a way to copy to mobile clipboard? I've been researching for days but haven't found a good solution. Clipboard.js doesn't seem to work on mobile, giving me an error "no support :("

I'm currently using the following function:

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

Works like a charm on chrome on my desktop. But on chrome mobile, nothing gets copied.

Is there a solution out there?

like image 334
Jackson Cunningham Avatar asked Mar 14 '16 19:03

Jackson Cunningham


People also ask

What can I use instead of execCommand copy?

The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful.

Can I use document execCommand?

The execCommand() method is deprecated. Do NOT use it. The applets property returns an empty HTMLCollection in all new browsers. The <applet> element is not supported in HTML5.

How do I copy text to clipboard?

Copying Text to the ClipboardCTRL+C to copy. CTRL+X to cut. CTRL+V to paste.


1 Answers

According to MDN, document.execCommand('copy') is available in the following mobile browsers:

  • Chrome for Android 42+
  • Firefox Mobile (Gecko) 41+

Note that this does not include the iOS Chrome or Firefox, which per-Apple's requirement, both must use the iOS supplied WebKit. Until iOS Safari supports it, iOS Chrome and iOS Firefox probably cannot.

Update:

Safari on iOS 10+ supports cut and copy

like image 174
Alexander O'Mara Avatar answered Sep 28 '22 06:09

Alexander O'Mara