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.
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.
The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With