10 lines to copy any text to the clipboard

Damien Cassou damien at cassou.me
Fri Aug 4 09:38:32 UTC 2017


Hi,

I would like my add-on to add some text to the clipboard. The code of my
extension to do that is quite complex:

    /**
     * Copy `text` to the clipboard
     */
    function copyText (text) {
      let textarea = document.createElement('textarea')
      textarea.textContent = text
    
      // hide the textarea
      textarea.setAttribute('style', 'height: 0 !important; width: 0 !important; border: none !important; z-index: -9999999;')
      document.querySelector('body').appendChild(textarea)
    
      textarea.select()
      document.execCommand('Copy')
      textarea.remove()
    }

Is there a simpler way?

Thanks

-- 
Damien Cassou
http://damiencassou.seasidehosting.st

"Success is the ability to go from one failure to another without
losing enthusiasm." --Winston Churchill


More information about the Dev-addons mailing list