11

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.

silverlight513
  • 5,268
  • 4
  • 26
  • 38
  • did you try `typeof document.execCommand !== 'undefined' ` ? – Zamboney Mar 22 '16 at 12:14
  • 1
    As I said in the question, safari has the function document.execCommand but doesn't support the parameter 'copy'. That's why I'm thinking of going down the route of browser detection. It also doesn't throw an error when trying to use the function with that param. – silverlight513 Mar 22 '16 at 12:25
  • It looks to me like there's no reliable way other than user agent sniffing. But (and I realize it's 5 years later!) support for this is now ubiquitous; nothing that I can find released later than mid-2016 lacks support, so in my opinion detecting support is no longer necessary. – tremby May 26 '21 at 22:06

1 Answers1

5

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
}
Yaroslav Rogoza
  • 985
  • 3
  • 12
  • 19
  • Firefox (v48) returns false and a warning when I tried it in the console just then. According to MDN, firefox has supported the command since v41 - https://developer.mozilla.org/en/docs/Web/API/Document/execCommand – silverlight513 Aug 12 '16 at 14:07
  • Yep, got the same problem. The interesting fact that FF v47 and FF v49 returns `true`. Looks like a bug in v48. – Yaroslav Rogoza Aug 12 '16 at 14:55