// Offscreen document script — audit fix HV-2c. // // The MV3 service worker cannot reliably write the clipboard itself (no DOM // focus), and `chrome.scripting.executeScript` into the *active tab* fails on // restricted pages (chrome://, the web store) or when no tab exists — which is // exactly when a stale password could be left on the clipboard forever. An // offscreen document is a stable, extension-owned surface that can always // service the clear. // // Loaded on demand by the background's onAlarm handler (clipboard.ts) via // chrome.offscreen.createDocument({ reasons: ["CLIPBOARD"] }). chrome.runtime.onMessage.addListener( (msg: unknown, _sender, sendResponse: (r: unknown) => void) => { const type = (msg as { type?: string } | null)?.type; if (type !== "CLEAR_CLIPBOARD") return undefined; // navigator.clipboard.writeText("") clears the platform clipboard. // The offscreen document is extension-origin, so no user gesture is // required under the CLIPBOARD offscreen reason. navigator.clipboard .writeText("") .then(() => sendResponse({ ok: true })) .catch((err: unknown) => { // Fallback for engines where writeText("") is rejected: textarea + // execCommand. Deprecated but still functional in offscreen docs. try { const ta = document.createElement("textarea"); ta.value = " "; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); sendResponse({ ok: true, via: "execCommand" }); } catch { sendResponse({ ok: false, error: err instanceof Error ? err.message : "clipboard_clear_failed", }); } }); return true; // async sendResponse }, );