Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Last active April 7, 2020 13:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save changhuixu/7172a29ff29bbdc3b8b6cad6f92c69dd to your computer and use it in GitHub Desktop.
Save changhuixu/7172a29ff29bbdc3b8b6cad6f92c69dd to your computer and use it in GitHub Desktop.
JavaScript Copy To Clipboard Example
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