document.execCommand('copy') not working on Chrome

前端 未结 3 1180
遇见更好的自我
遇见更好的自我 2021-02-19 17:10

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

3条回答
  •  终归单人心
    2021-02-19 17:43

    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

提交回复
热议问题