On Chrome only document.execCommand(\'copy\')
returns true but does not copy the text, it clears the clipboard.
I can\'t find anyone who\'s had the same pro
For people reading this question in 2020, if you're having trouble with document.execCommand('copy')
, you may want to try using the Clipboard API.
Per Mozilla:
There are two ways browser extensions can interact with the system clipboard: the Document.execCommand() method and the modern asynchronous Clipboard API.
Also per Mozilla, document.execCommand()
is now obsolete:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
With the Clipboard API, writing text to the clipboard is particularly easy:
const textToCopy = 'Hello there!'
navigator.clipboard.writeText(textToCopy)
.then(() => { alert(`Copied!`) })
.catch((error) => { alert(`Copy failed! ${error}`) })
More info:
Mozilla's discussion of the two clipboard systems
Google's discussion of the two clipboard systems
Another good discussion of the Clipboard API
CanIUse