copy.ts

1.5 KB · raw

1/**2 * Popup-side copy helper.3 *4 * MV3 service workers can't reliably write the clipboard from a non-focused5 * tab — the SW path's `chrome.scripting.executeScript` into the active tab6 * loses the popup's user gesture and the page document is not focused, so7 * `navigator.clipboard.writeText` rejects with NotAllowed. The popup itself8 * is a focused document with a fresh user gesture and `clipboardWrite`9 * permission, so it can call the API directly. We then notify the SW with10 * `alreadyWritten: true` so it skips its own write and only schedules the11 * auto-clear timer.12 */1314import { sendMessage } from "./App";1516export async function popupCopy(17  text: string,18  label: string,19  entryId?: string,20): Promise<boolean> {21  let alreadyWritten = false;22  try {23    await navigator.clipboard.writeText(text);24    alreadyWritten = true;25  } catch {26    // Some popup contexts (jsdom in tests, or rare permission-denied edge27    // cases) reject the direct write. Fall through to the SW path.28  }2930  const response = await sendMessage({31    type: "COPY",32    payload: { text, label, alreadyWritten },33  });34  const ok = alreadyWritten || Boolean((response as { ok?: boolean })?.ok);35  const canaryLabel = label.toLowerCase();36  if (ok && entryId && (canaryLabel === "password" || canaryLabel === "username")) {37    void sendMessage({38      type: "FIRE_CANARY_PING",39      payload: {40        id: entryId,41        trigger: canaryLabel === "password" ? "password_copied" : "username_copied",42      },43    });44  }45  return ok;46}