2021-05-11 13:34:23 +02:00
|
|
|
/**
|
|
|
|
* Copies set text to clipboard.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* copies 'Hello World!' to the clipboard and prints "true":
|
|
|
|
* ```typescript
|
|
|
|
* console.log(copyToClipboard('Hello World!'));
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param text - The text to be copied to the clipboard.
|
|
|
|
* @returns true - If the copy operation is successful.
|
|
|
|
*/
|
2021-04-26 12:14:36 +02:00
|
|
|
function copyToClipboard(text: any): boolean {
|
|
|
|
// create our hidden div element
|
2021-04-29 19:10:39 +02:00
|
|
|
const hiddenCopy: HTMLDivElement = document.createElement('div');
|
2021-04-26 12:14:36 +02:00
|
|
|
// set the innerHTML of the div
|
|
|
|
hiddenCopy.innerHTML = text;
|
|
|
|
// set the position to be absolute and off the screen
|
2021-04-29 13:15:14 +02:00
|
|
|
hiddenCopy.classList.add('clipboard');
|
2021-04-26 12:14:36 +02:00
|
|
|
|
|
|
|
// check and see if the user had a text selection range
|
2021-04-29 13:15:14 +02:00
|
|
|
let currentRange: Range | boolean;
|
2021-04-26 12:14:36 +02:00
|
|
|
if (document.getSelection().rangeCount > 0) {
|
2021-05-10 18:15:25 +02:00
|
|
|
// the user has a text selection range, store it
|
|
|
|
currentRange = document.getSelection().getRangeAt(0);
|
|
|
|
// remove the current selection
|
|
|
|
window.getSelection().removeRange(currentRange);
|
2021-04-26 12:14:36 +02:00
|
|
|
} else {
|
|
|
|
// they didn't have anything selected
|
|
|
|
currentRange = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// append the div to the body
|
|
|
|
document.body.appendChild(hiddenCopy);
|
|
|
|
// create a selection range
|
2021-04-29 19:10:39 +02:00
|
|
|
const copyRange: Range = document.createRange();
|
2021-04-26 12:14:36 +02:00
|
|
|
// set the copy range to be the hidden div
|
|
|
|
copyRange.selectNode(hiddenCopy);
|
|
|
|
// add the copy range
|
|
|
|
window.getSelection().addRange(copyRange);
|
|
|
|
|
|
|
|
// since not all browsers support this, use a try block
|
|
|
|
try {
|
|
|
|
// copy the text
|
|
|
|
document.execCommand('copy');
|
|
|
|
} catch (err) {
|
2021-05-10 18:15:25 +02:00
|
|
|
window.alert('Your Browser Does not support this! Error : ' + err);
|
2021-04-26 12:14:36 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
// remove the selection range (Chrome throws a warning if we don't.)
|
|
|
|
window.getSelection().removeRange(copyRange);
|
|
|
|
// remove the hidden div
|
|
|
|
document.body.removeChild(hiddenCopy);
|
|
|
|
|
|
|
|
// return the old selection range
|
|
|
|
if (currentRange) {
|
|
|
|
window.getSelection().addRange(currentRange);
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2021-05-11 13:34:23 +02:00
|
|
|
/** @exports */
|
2021-05-10 18:15:25 +02:00
|
|
|
export { copyToClipboard };
|