Skip to content

Commit dc1c917

Browse files
⚡ Use navigator.clipboard
1 parent 7066cfb commit dc1c917

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

src/class/HTMLCodeBlockElement.ts

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,31 @@ export default class HTMLCodeBlockElement extends HTMLElement {
6262
/** Click event handler of copy button */
6363
#onClickButton = (() => {
6464
let key = -1;
65-
const textarea = document.createElement('textarea');
65+
const copy = (): Promise<void> => {
66+
const value = this.#value.replace(/\n$/, '');
6667

67-
return () => {
68+
if (navigator.clipboard){
69+
return navigator.clipboard.writeText(value);
70+
}
71+
72+
return new Promise((r) => {
73+
const textarea = document.createElement('textarea');
74+
75+
textarea.value = value;
76+
document.body.append(textarea);
77+
textarea.select();
78+
document.execCommand('copy');
79+
textarea.remove();
80+
r();
81+
});
82+
}
83+
84+
return async () => {
6885
clearTimeout(key);
6986

70-
textarea.value = this.#value.replace(/\n$/, '');
71-
document.body.append(textarea);
72-
textarea.select();
73-
document.execCommand('copy');
74-
textarea.remove();
75-
this.#copyButton.textContent = 'Copied!';
87+
await copy();
7688

89+
this.#copyButton.textContent = 'Copied!';
7790
key = window.setTimeout(() => {
7891
this.#copyButton.textContent = 'Copy';
7992
}, 1500);

0 commit comments

Comments
 (0)