Created
May 19, 2018 12:41
-
-
Save KEIII/af1d729bfcea371954f1c29613bc3637 to your computer and use it in GitHub Desktop.
copy to clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The core function is ported from clipboard.js | |
// https://github.com/zenorocha/clipboard.js/ | |
const isCopySupported = (doc: Document): boolean => { | |
return Boolean(doc.queryCommandSupported && doc.queryCommandSupported('copy')); | |
}; | |
/** | |
* Creates a fake textarea element, sets its value from `text` property, | |
* and makes a selection on it. | |
*/ | |
const createTempTextArea = (doc: Document, win: Window): HTMLTextAreaElement => { | |
const isRTL = doc.documentElement.getAttribute('dir') === 'rtl'; | |
let ta: HTMLTextAreaElement; | |
ta = doc.createElement('textarea'); | |
// Prevent zooming on iOS | |
ta.style.fontSize = '12pt'; | |
// Reset box model | |
ta.style.border = '0'; | |
ta.style.padding = '0'; | |
ta.style.margin = '0'; | |
// Move element out of screen horizontally | |
ta.style.position = 'absolute'; | |
ta.style[isRTL ? 'right' : 'left'] = '-9999px'; | |
// Move element to the same position vertically | |
const yPosition = win.pageYOffset || doc.documentElement.scrollTop; | |
ta.style.top = yPosition + 'px'; | |
ta.setAttribute('readonly', ''); | |
return ta; | |
}; | |
/** | |
* Copy text to clipboard. | |
* @throws string Exception if failed | |
*/ | |
export const copyToClipboard = (text: string, doc: Document, win: Window): void => { | |
let succeeded: boolean = false; | |
let error: string | null = null; | |
if (!isCopySupported(doc)) { | |
error = 'NOT_SUPPORTED'; | |
} else { | |
const textarea = createTempTextArea(doc, win); | |
textarea.value = text; | |
doc.body.appendChild(textarea); | |
// check if there is any content selected previously | |
const originalSelection = doc.getSelection().rangeCount > 0 | |
? doc.getSelection().getRangeAt(0) | |
: false; | |
// select the <textarea> content | |
textarea.select(); | |
textarea.setSelectionRange(0, textarea.value.length); | |
try { | |
succeeded = doc.execCommand('copy'); | |
} catch (e) { | |
error = e; | |
} | |
doc.body.removeChild(textarea); | |
// restore original selection | |
if (originalSelection) { | |
doc.getSelection().removeAllRanges(); // unselect everything on the HTML document | |
doc.getSelection().addRange(originalSelection); // restore the original selection | |
} | |
} | |
if (!succeeded) { | |
throw error; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment