Enea Xharja Logo

Copy to Clipboard

js
1const copyToClipboard = str => {
2 const { clipboard } = window.navigator;
3
4 // if clipboard API not supported
5 if (!clipboard || typeof clipboard.writeText !== `function`) {
6 const textarea = document.createElement(`textarea`);
7 textarea.value = str;
8 textarea.setAttribute(`readonly`, true);
9 textarea.setAttribute(`contenteditable`, true);
10 textarea.style.position = `absolute`;
11 textarea.style.left = `-9999px`;
12 document.body.appendChild(textarea);
13 textarea.select();
14 const range = document.createRange();
15 const sel = window.getSelection();
16 sel.removeAllRanges();
17 sel.addRange(range);
18 textarea.setSelectionRange(0, textarea.value.length);
19 document.execCommand(`copy`);
20 document.body.removeChild(textarea);
21
22 return Promise.resolve(true);
23 }
24
25 return clipboard.writeText(str);
26};

You can find this snippet in action here.

© 2021 Enea Xharja