|
1 | 1 | document.addEventListener('DOMContentLoaded', function () { |
| 2 | + function copyText(text) { |
| 3 | + if (navigator.clipboard && window.isSecureContext) { |
| 4 | + return navigator.clipboard.writeText(text); |
| 5 | + } |
| 6 | + |
| 7 | + return new Promise(function (resolve, reject) { |
| 8 | + var textArea = document.createElement('textarea'); |
| 9 | + textArea.value = text; |
| 10 | + textArea.setAttribute('readonly', ''); |
| 11 | + textArea.style.position = 'fixed'; |
| 12 | + textArea.style.opacity = '0'; |
| 13 | + document.body.appendChild(textArea); |
| 14 | + textArea.select(); |
| 15 | + |
| 16 | + try { |
| 17 | + if (!document.execCommand('copy')) { |
| 18 | + throw new Error('Copy command failed'); |
| 19 | + } |
| 20 | + resolve(); |
| 21 | + } catch (error) { |
| 22 | + reject(error); |
| 23 | + } finally { |
| 24 | + textArea.remove(); |
| 25 | + } |
| 26 | + }); |
| 27 | + } |
| 28 | + |
2 | 29 | document.querySelectorAll('.copy-cmd').forEach(function (cell) { |
3 | 30 | cell.addEventListener('click', function () { |
4 | | - navigator.clipboard.writeText(cell.dataset.cmd).then(function () { |
| 31 | + copyText(cell.dataset.cmd).then(function () { |
5 | 32 | cell.classList.add('copied'); |
6 | 33 | setTimeout(function () { cell.classList.remove('copied'); }, 1500); |
7 | 34 | }); |
8 | 35 | }); |
9 | 36 | }); |
| 37 | + |
| 38 | + document.querySelectorAll('#main pre').forEach(function (codeBlock) { |
| 39 | + var wrapper = document.createElement('div'); |
| 40 | + var button = document.createElement('button'); |
| 41 | + |
| 42 | + wrapper.className = 'code-block'; |
| 43 | + codeBlock.parentNode.insertBefore(wrapper, codeBlock); |
| 44 | + wrapper.appendChild(codeBlock); |
| 45 | + |
| 46 | + button.className = 'copy-code-button'; |
| 47 | + button.type = 'button'; |
| 48 | + button.setAttribute('aria-label', 'Copy code to clipboard'); |
| 49 | + wrapper.appendChild(button); |
| 50 | + |
| 51 | + button.addEventListener('click', function () { |
| 52 | + copyText(codeBlock.textContent).then(function () { |
| 53 | + button.setAttribute('aria-label', 'Code copied'); |
| 54 | + button.classList.add('copied'); |
| 55 | + setTimeout(function () { |
| 56 | + button.setAttribute('aria-label', 'Copy code to clipboard'); |
| 57 | + button.classList.remove('copied'); |
| 58 | + }, 1500); |
| 59 | + }); |
| 60 | + }); |
| 61 | + }); |
10 | 62 | }); |
0 commit comments