Last active
April 7, 2020 13:53
-
-
Save changhuixu/7172a29ff29bbdc3b8b6cad6f92c69dd to your computer and use it in GitHub Desktop.
JavaScript Copy To Clipboard Example
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
copy() { | |
try { | |
if ((navigator as any).clipboard) { | |
(navigator as any).clipboard.writeText(this.couponCode); | |
} else if ((window as any).clipboardData) { // IE | |
(window as any).clipboardData.setData('text', this.couponCode); | |
} else { // other browsers, iOS, Mac OS | |
this.copyToClipboard(this.inputEl.nativeElement); | |
} | |
this.tooltipText = 'Copied to Clipboard.'; // copy succeed. | |
} catch (e) { | |
this.tooltipText = 'Please copy coupon manually.'; // copy failed. | |
} | |
} | |
private copyToClipboard(el: HTMLInputElement) { | |
const oldContentEditable = el.contentEditable; | |
const oldReadOnly = el.readOnly; | |
try { | |
el.contentEditable = 'true'; // specific to iOS | |
el.readOnly = false; | |
this.copyNodeContentsToClipboard(el); | |
} finally { | |
el.contentEditable = oldContentEditable; | |
el.readOnly = oldReadOnly; | |
} | |
} | |
private copyNodeContentsToClipboard(el: HTMLInputElement) { | |
const range = document.createRange(); | |
const selection = window.getSelection(); | |
range.selectNodeContents(el); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
el.setSelectionRange(0, 999999); | |
document.execCommand('copy'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment