Skip to content

Commit

Permalink
add copy-to-clipboard fallback if navigator.clipboard is not available
Browse files Browse the repository at this point in the history
  • Loading branch information
lacksfish committed Dec 6, 2023
1 parent d083be1 commit c6f477e
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/app/shared/directive/clipboard.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,37 @@ export class ClipboardDirective {
@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload || !navigator.clipboard) {
return;

if (!this.payload) return;

if (navigator.clipboard) {
this.copyUsingClipboardAPI();
} else {
this.copyUsingFallbackMethod();
}
navigator.clipboard.writeText(this.payload.toString()).then(() => {
this.copied.emit(this.payload.toString());
}, (err) => {
this.copied.emit('Error could not copy text: ' + JSON.stringify(err));
});
}

private copyUsingFallbackMethod(): void {
const input = document.createElement('textarea');
input.innerHTML = this.payload;
document.body.appendChild(input);
input.select();

try {
const result = document.execCommand('copy');
if (result) {
this.copied.emit(this.payload.toString());
} else {
this.copied.emit('Error could not copy text.');
}
} finally {
document.body.removeChild(input);
}
}

private copyUsingClipboardAPI(): void {
navigator.clipboard.writeText(this.payload.toString())
.then(() => this.copied.emit(this.payload.toString()))
.catch((error) => this.copied.emit('Error could not copy text: ' + JSON.stringify(error)));
}
}

0 comments on commit c6f477e

Please sign in to comment.