Skip to content

Instantly share code, notes, and snippets.

@eugenemtn
Last active December 24, 2019 14:56
Show Gist options
  • Save eugenemtn/3039545abf8c5b67c78e3720c5bf210d to your computer and use it in GitHub Desktop.
Save eugenemtn/3039545abf8c5b67c78e3720c5bf210d to your computer and use it in GitHub Desktop.
function clipBoardWriteValue(value, ref) {
// If we have the navigator.clipboard then it is possible to write a string to a clipboard directly
if (navigator.clipboard) {
navigator.clipboard.writeText(value)
.then(() => {
this.showCopiedBadge();
});
return;
}
// Otherwise, we need to select some node's content and run document.execCommand('copy')
// Get the element which will contain a value, you like to copy whichever method you like
const el = document.getElementById('target');
if (document.body.createTextRange) {
// This case for IE, not tested yet
const range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
} else if (window.getSelection) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
selection.removeAllRanges();
selection.addRange(range);
} else {
console.warn('Could not select text in node: Unsupported browser.');
return;
}
try {
document.execCommand('copy');
// Succesfully copied
} catch (err) {
console.log('Unable to copy');
// Something went wrong
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment