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>
`)
Written by ms_bit
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript es6 es2015 copy clipboard
Authors
Related Tags
#javascript es6 es2015 copy clipboard
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#