Last Updated: July 12, 2018
·
143
· ms_bit

Copy text (with markdowns) to clipboard with Javascript

That is a simple es2015 module to copy some text (with html markdowns) to the user clipboard.

export default text => new Promise((resolve) => {
    let range;
    const textarea = document.createElement('pre')
    textarea.style.fontFamily = 'monospace'
    textarea.style.opacity = '0'
    textarea.style.position = 'fixed'
    textarea.style.top = '0'
    textarea.style.left = '-2000px'

    document.body.appendChild(textarea)    
    textarea.innerHTML = text
    textarea.focus()

    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.selectNodeContents(textarea);
        let sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(textarea);
        range.select();
    }

    document.execCommand('copy')

    setTimeout(() => {
        document.body.removeChild(textarea)
        resolve()
    }, 500)
})

Usage:

import copyToClipboard from './some/path/clipboard.js'

copyToClipboard(`
  <h1>Title</h1>
  <p>text</p>
`)