| export async function copyToClipboard(text: string): Promise<boolean> { |
| |
| |
| |
| |
| if (globalThis.isSecureContext === true && navigator.clipboard?.writeText) { |
| try { |
| await navigator.clipboard.writeText(text); |
| return true; |
| } catch { |
| |
| |
| |
| } |
| } |
| return legacyCopy(text); |
| } |
|
|
| |
| |
| function legacyCopy(text: string): boolean { |
| if (typeof document === "undefined" || !document.body) return false; |
| const textarea = document.createElement("textarea"); |
| textarea.value = text; |
| textarea.setAttribute("readonly", ""); |
| textarea.setAttribute("aria-hidden", "true"); |
| textarea.style.position = "fixed"; |
| textarea.style.top = "0"; |
| textarea.style.left = "-9999px"; |
| textarea.style.width = "1em"; |
| textarea.style.height = "1em"; |
| |
| |
| textarea.style.fontSize = "2em"; |
| textarea.style.padding = "0"; |
| textarea.style.border = "none"; |
| textarea.style.outline = "none"; |
| textarea.style.boxShadow = "none"; |
| textarea.style.background = "transparent"; |
| textarea.style.opacity = "0"; |
| textarea.style.pointerEvents = "none"; |
|
|
| const activeElement = document.activeElement as Element | null; |
| const selection = document.getSelection(); |
| let savedRange: Range | null = null; |
| if (selection && selection.rangeCount > 0) savedRange = selection.getRangeAt(0); |
|
|
| document.body.appendChild(textarea); |
| textarea.focus({ preventScroll: true }); |
| textarea.select(); |
| textarea.setSelectionRange(0, text.length); |
|
|
| let ok = false; |
| try { |
| ok = document.execCommand("copy"); |
| } catch { |
| |
| } |
|
|
| document.body.removeChild(textarea); |
| if (savedRange && selection) { |
| selection.removeAllRanges(); |
| selection.addRange(savedRange); |
| } |
| if (activeElement instanceof HTMLElement && typeof activeElement.focus === "function") { |
| activeElement.focus(); |
| } |
| return ok; |
| } |
|
|