offscreen.ts

1.8 KB · raw

1// Offscreen document script — audit fix HV-2c.2//3// The MV3 service worker cannot reliably write the clipboard itself (no DOM4// focus), and `chrome.scripting.executeScript` into the *active tab* fails on5// restricted pages (chrome://, the web store) or when no tab exists — which is6// exactly when a stale password could be left on the clipboard forever. An7// offscreen document is a stable, extension-owned surface that can always8// service the clear.9//10// Loaded on demand by the background's onAlarm handler (clipboard.ts) via11// chrome.offscreen.createDocument({ reasons: ["CLIPBOARD"] }).1213chrome.runtime.onMessage.addListener(14  (msg: unknown, _sender, sendResponse: (r: unknown) => void) => {15    const type = (msg as { type?: string } | null)?.type;16    if (type !== "CLEAR_CLIPBOARD") return undefined;17    // navigator.clipboard.writeText("") clears the platform clipboard.18    // The offscreen document is extension-origin, so no user gesture is19    // required under the CLIPBOARD offscreen reason.20    navigator.clipboard21      .writeText("")22      .then(() => sendResponse({ ok: true }))23      .catch((err: unknown) => {24        // Fallback for engines where writeText("") is rejected: textarea +25        // execCommand. Deprecated but still functional in offscreen docs.26        try {27          const ta = document.createElement("textarea");28          ta.value = " ";29          document.body.appendChild(ta);30          ta.select();31          document.execCommand("copy");32          ta.remove();33          sendResponse({ ok: true, via: "execCommand" });34        } catch {35          sendResponse({36            ok: false,37            error: err instanceof Error ? err.message : "clipboard_clear_failed",38          });39        }40      });41    return true; // async sendResponse42  },43);