Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect copy to clipboard functionality before using it

I'm trying to create a copy function in pure JS, so no flash. The problem I've got is that I don't want to show the copy button when the browser doesn't support copying to clipboard.

I'm using the document.execCommand('copy') method to do the copying to clipboard but the support for this isn't the best. For example, safari has the execCommand function but doesn't support the copy parameter. This means that I can't simply just check if the function exists.

Because of this dodgy support I think I'm going to have to go in the way of browser detection, just like github does which I came across from looking at a zeroclipboard issue. Here is the implementation I found.

Is there a correct way to detect the user agent? I'd rather not use NavigatorID.userAgent as that is deprecated according to MDN.

like image 305
silverlight513 Avatar asked Mar 22 '16 12:03

silverlight513


People also ask

How do I add copy to clipboard button on page?

Whether it is a sample of code or it is the User's own information, we can create a copy button to copy data to the clipboard using the navigator. clipboard. writeText() function. This function writes the data fed to it as a parameter into the clipboard.

What can I use instead of execCommand?

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

When it says copied to clipboard where does it go?

The clipboard is not an actual place on the phone you can access in a way other than by pasting what you have copied to it. The clipboard is a memory space only that is temporary and is cleared out when you copy something else to it since it holds one thing usually, or cleared when you restart the device.


1 Answers

I noticed that in Safari prior to version 10 (tested on 9.0 and 9.1) the following construction

document.execCommand('copy');

will return false. This fact can be used for checking compatibility in Safari.

if (false == document.execCommand('copy')) {
    // Logic for handling the copy functionality in some other way
}
like image 83
Yaroslav Rogoza Avatar answered Nov 15 '22 18:11

Yaroslav Rogoza