(text, button)
| 2 | |
| 3 | // Copy to clipboard function |
| 4 | function copyToClipboard(text, button) { |
| 5 | function showSuccessMessage() { |
| 6 | if (button) { |
| 7 | const originalText = button.textContent; |
| 8 | const originalColor = button.style.color; |
| 9 | button.textContent = "✓ Copied"; |
| 10 | button.style.color = "green"; |
| 11 | setTimeout(() => { |
| 12 | button.textContent = originalText; |
| 13 | button.style.color = originalColor; |
| 14 | }, 1500); |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | // Check if modern clipboard API is available |
| 19 | if (navigator.clipboard && navigator.clipboard.writeText) { |
| 20 | navigator.clipboard |
| 21 | .writeText(text) |
| 22 | .then(function () { |
| 23 | showSuccessMessage(); |
| 24 | console.log("Copied to clipboard:", text); |
| 25 | }) |
| 26 | .catch(function (err) { |
| 27 | console.error("Failed to copy text with clipboard API: ", err); |
| 28 | // Fall back to legacy method |
| 29 | fallbackCopy(); |
| 30 | }); |
| 31 | } else { |
| 32 | // Use fallback method directly |
| 33 | fallbackCopy(); |
| 34 | } |
| 35 | |
| 36 | function fallbackCopy() { |
| 37 | try { |
| 38 | const textArea = document.createElement("textarea"); |
| 39 | textArea.value = text; |
| 40 | textArea.style.position = "fixed"; |
| 41 | textArea.style.left = "-9999px"; |
| 42 | textArea.style.top = "-9999px"; |
| 43 | document.body.appendChild(textArea); |
| 44 | textArea.focus(); |
| 45 | textArea.select(); |
| 46 | |
| 47 | const successful = document.execCommand("copy"); |
| 48 | document.body.removeChild(textArea); |
| 49 | |
| 50 | if (successful) { |
| 51 | showSuccessMessage(); |
| 52 | console.log("Copied to clipboard (fallback):", text); |
| 53 | } else { |
| 54 | console.error("Failed to copy text with fallback method"); |
| 55 | if (button) { |
| 56 | button.textContent = "✗ Failed"; |
| 57 | button.style.color = "red"; |
| 58 | setTimeout(() => { |
| 59 | button.textContent = button.getAttribute("title") || "Copy"; |
| 60 | button.style.color = ""; |
| 61 | }, 1500); |
no test coverage detected