Skip to content

Instantly share code, notes, and snippets.

@fmal
Created December 1, 2017 14:01
Show Gist options
  • Select an option

  • Save fmal/28b637cab5b6745c685f60c7377bb3ad to your computer and use it in GitHub Desktop.

Select an option

Save fmal/28b637cab5b6745c685f60c7377bb3ad to your computer and use it in GitHub Desktop.
function createNode(text) {
const node = document.createElement('pre');
node.style.width = '1px';
node.style.height = '1px';
node.style.position = 'fixed';
node.style.top = '5px';
node.textContent = text;
return node;
}
function copyNode(node) {
const selection = document.getSelection();
selection.removeAllRanges();
const range = document.createRange();
range.selectNodeContents(node);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
}
export default function copyToClipboard(text) {
return new Promise((resolve, reject) => {
try {
const node = createNode(text);
document.body.appendChild(node);
copyNode(node);
document.body.removeChild(node);
resolve();
} catch (e) {
reject(e);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment