|
61 | 61 | btn.addEventListener('click', () => { |
62 | 62 | const code = pre.querySelector('code'); |
63 | 63 | const text = code ? code.innerText : pre.innerText; |
64 | | - navigator.clipboard.writeText(text).then(() => { |
| 64 | + |
| 65 | + const markCopied = () => { |
65 | 66 | btn.textContent = 'Copied!'; |
66 | 67 | btn.classList.add('copied'); |
67 | 68 | setTimeout(() => { |
68 | 69 | btn.textContent = 'Copy'; |
69 | 70 | btn.classList.remove('copied'); |
70 | 71 | }, 2000); |
71 | | - }).catch(() => { |
| 72 | + }; |
| 73 | + |
| 74 | + const markFailed = () => { |
| 75 | + btn.textContent = 'Copy failed'; |
| 76 | + btn.classList.add('copy-error'); |
| 77 | + setTimeout(() => { |
| 78 | + btn.textContent = 'Copy'; |
| 79 | + btn.classList.remove('copy-error'); |
| 80 | + }, 2000); |
| 81 | + }; |
| 82 | + |
| 83 | + const fallbackCopy = () => { |
72 | 84 | const ta = document.createElement('textarea'); |
73 | 85 | ta.value = text; |
74 | 86 | ta.style.position = 'fixed'; |
75 | 87 | ta.style.opacity = '0'; |
76 | 88 | document.body.appendChild(ta); |
77 | 89 | ta.select(); |
78 | 90 | try { |
79 | | - document.execCommand('copy'); |
80 | | - btn.textContent = 'Copied!'; |
81 | | - btn.classList.add('copied'); |
82 | | - setTimeout(() => { |
83 | | - btn.textContent = 'Copy'; |
84 | | - btn.classList.remove('copied'); |
85 | | - }, 2000); |
| 91 | + const copied = document.execCommand('copy'); |
| 92 | + if (copied) markCopied(); |
| 93 | + else markFailed(); |
86 | 94 | } catch (e) { |
87 | | - btn.textContent = 'Copy failed'; |
88 | | - btn.classList.add('copy-error'); |
89 | | - setTimeout(() => { |
90 | | - btn.textContent = 'Copy'; |
91 | | - btn.classList.remove('copy-error'); |
92 | | - }, 2000); |
| 95 | + markFailed(); |
| 96 | + } finally { |
| 97 | + document.body.removeChild(ta); |
93 | 98 | } |
94 | | - document.body.removeChild(ta); |
95 | | - }); |
| 99 | + }; |
| 100 | + |
| 101 | + if (navigator.clipboard?.writeText) { |
| 102 | + navigator.clipboard.writeText(text).then(markCopied).catch(fallbackCopy); |
| 103 | + } else { |
| 104 | + fallbackCopy(); |
| 105 | + } |
96 | 106 | }); |
97 | 107 |
|
98 | 108 | wrapper.appendChild(btn); |
|
0 commit comments