|
| 1 | +/** |
| 2 | + * Clipboard write with a fallback for non-secure contexts. |
| 3 | + * |
| 4 | + * `navigator.clipboard` is only defined in secure contexts (https, localhost, |
| 5 | + * 127.0.0.1). On plain http to any other host it is undefined, so both |
| 6 | + * direct `navigator.clipboard.writeText` calls and xterm's `ClipboardAddon` |
| 7 | + * OSC 52 handler throw `TypeError: Cannot read properties of undefined`. |
| 8 | + * |
| 9 | + * The fallback selects a hidden textarea and runs `document.execCommand("copy")`, |
| 10 | + * which works in any browsing context at the cost of a brief focus steal. |
| 11 | + */ |
| 12 | + |
| 13 | +import type { |
| 14 | + IClipboardProvider, |
| 15 | + ClipboardSelectionType, |
| 16 | +} from "@xterm/addon-clipboard"; |
| 17 | + |
| 18 | +/** Write `text` to the system clipboard, falling back to execCommand when |
| 19 | + * navigator.clipboard is unavailable or throws. Throws if both paths fail. */ |
| 20 | +export async function writeTextToClipboard(text: string): Promise<void> { |
| 21 | + if (navigator.clipboard?.writeText) { |
| 22 | + try { |
| 23 | + await navigator.clipboard.writeText(text); |
| 24 | + return; |
| 25 | + } catch { |
| 26 | + // Fall through to execCommand — navigator.clipboard can reject for |
| 27 | + // reasons other than missing secure context (permission denied, etc.). |
| 28 | + } |
| 29 | + } |
| 30 | + const textarea = document.createElement("textarea"); |
| 31 | + textarea.value = text; |
| 32 | + textarea.style.position = "fixed"; |
| 33 | + textarea.style.opacity = "0"; |
| 34 | + document.body.appendChild(textarea); |
| 35 | + try { |
| 36 | + textarea.select(); |
| 37 | + const ok = document.execCommand("copy"); |
| 38 | + if (!ok) throw new Error("clipboard access blocked"); |
| 39 | + } finally { |
| 40 | + document.body.removeChild(textarea); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/** xterm `IClipboardProvider` that uses `writeTextToClipboard` for writes |
| 45 | + * (survives non-secure contexts) and returns empty on reads when |
| 46 | + * navigator.clipboard is unavailable. OSC 52 read queries (`?`) are rare |
| 47 | + * and have no safe fallback. */ |
| 48 | +export class SafeClipboardProvider implements IClipboardProvider { |
| 49 | + public async readText(selection: ClipboardSelectionType): Promise<string> { |
| 50 | + if (selection !== "c") return ""; |
| 51 | + if (!navigator.clipboard?.readText) return ""; |
| 52 | + return navigator.clipboard.readText(); |
| 53 | + } |
| 54 | + |
| 55 | + public async writeText( |
| 56 | + selection: ClipboardSelectionType, |
| 57 | + text: string, |
| 58 | + ): Promise<void> { |
| 59 | + if (selection !== "c") return; |
| 60 | + await writeTextToClipboard(text); |
| 61 | + } |
| 62 | +} |
0 commit comments