Files
opencode-chrome/extension/content.js
T

600 lines
26 KiB
JavaScript

// Content script: accessibility tree (read_page), element refs, natural
// language element search (find), form filling, page text, and point/ref
// geometry for the background worker. Runs in the extension's isolated world.
(function () {
if (window.__ocbContentLoaded) return;
window.__ocbContentLoaded = true;
// --- Element refs ---
// Stable per page: an element keeps its ref across calls, held weakly so a
// removed element can be garbage collected.
let refCounter = 0;
const elementMap = {}; // ref -> WeakRef<Element>
const reverseMap = new WeakMap(); // Element -> ref
function getOrAssignRef(el) {
const existing = reverseMap.get(el);
if (existing && elementMap[existing]?.deref() === el) return existing;
const ref = `ref_${++refCounter}`;
elementMap[ref] = new WeakRef(el);
reverseMap.set(el, ref);
return ref;
}
function resolveRef(ref) {
const el = elementMap[ref]?.deref();
if (!el) {
delete elementMap[ref];
return null;
}
return el;
}
// --- Roles and names ---
// Matches what the official extension prints: HTML-derived roles (no
// separate searchbox/spinbutton/slider), "generic" for everything without
// one, and names in its order (placeholder before <label for>, the value
// after both).
const TAG_TO_ROLE = {
a: "link", button: "button", textarea: "textbox", select: "combobox", img: "image",
h1: "heading", h2: "heading", h3: "heading", h4: "heading", h5: "heading", h6: "heading",
nav: "navigation", main: "main", header: "banner", footer: "contentinfo", aside: "complementary",
section: "region", article: "article", form: "form", label: "label", ul: "list", ol: "list",
li: "listitem", table: "table", dialog: "dialog"
};
const INPUT_ROLES = { checkbox: "checkbox", radio: "radio", button: "button", submit: "button", reset: "button", image: "button", file: "button" };
const SKIP_TAGS = new Set(["script", "style", "noscript", "template", "head", "meta", "link", "br", "title", "ocb-agent-overlay"]);
const INTERACTIVE_ROLES = new Set([
"button", "link", "textbox", "searchbox", "checkbox", "radio", "tab", "menuitem", "menuitemcheckbox",
"menuitemradio", "switch", "combobox", "slider", "spinbutton", "option", "treeitem", "listbox"
]);
function getRole(el) {
const explicit = el.getAttribute("role");
if (explicit && explicit.trim()) return explicit.trim().split(/\s+/)[0];
const tag = el.tagName.toLowerCase();
if (tag === "input") return INPUT_ROLES[str(el.type).toLowerCase()] || "textbox";
if (tag === "a" && !el.hasAttribute("href")) return "generic";
return TAG_TO_ROLE[tag] || "generic";
}
const str = (v) => (typeof v === "string" ? v : "");
const clean = (s) => String(s || "").replace(/\s+/g, " ").trim();
const cap = (s) => (s.length > 100 ? s.slice(0, 100) + "..." : s);
function directText(el) {
let t = "";
for (const n of el.childNodes) if (n.nodeType === 3) t += n.textContent;
return clean(t);
}
function getAccessibleName(el, role = getRole(el)) {
const aria = el.getAttribute("aria-label");
if (aria && aria.trim()) return cap(clean(aria));
const labelledBy = el.getAttribute("aria-labelledby");
if (labelledBy) {
const t = labelledBy.split(/\s+/).map((id) => clean(document.getElementById(id)?.textContent)).filter(Boolean).join(" ");
if (t) return cap(t);
}
const tag = el.tagName.toLowerCase();
if (tag === "select") {
const o = el.options[el.selectedIndex] || el.options[0];
return o ? cap(clean(o.textContent)) : "";
}
if (tag === "input" || tag === "textarea") {
const type = str(el.type).toLowerCase();
if (type === "file") return "";
if (str(el.placeholder).trim()) return cap(clean(el.placeholder));
if (el.id) {
const label = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
if (label && clean(label.textContent)) return cap(clean(label.textContent));
}
if (str(el.title).trim()) return cap(clean(el.title));
if (el.value) return type === "password" ? "[value redacted]" : cap(clean(el.value));
return "";
}
if (tag === "img") return cap(clean(str(el.alt) || str(el.title)));
if (role === "link" && str(el.title).trim()) return cap(clean(el.title));
if (["link", "button", "heading", "option"].includes(role)) {
const t = clean(el.textContent);
if (t) return cap(t);
} else {
const t = directText(el);
if (t) return cap(t);
}
return cap(clean(str(el.title)));
}
function isInteractive(el) {
return INTERACTIVE_ROLES.has(getRole(el));
}
function isVisible(el) {
const style = getComputedStyle(el);
if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
if (parseFloat(style.opacity) === 0) return false;
const r = el.getBoundingClientRect();
if (r.width === 0 && r.height === 0 && style.overflow !== "visible") return false;
return true;
}
function inViewport(el) {
const r = el.getBoundingClientRect();
return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
}
// --- read_page ---
const q = (v) => String(v).replace(/"/g, '\\"');
function describeLine(el, role, name) {
const tag = el.tagName.toLowerCase();
let line = role;
if (name) line += ` "${q(name)}"`;
line += ` [${getOrAssignRef(el)}]`;
if (tag === "a" && el.hasAttribute("href")) line += ` href="${q(el.getAttribute("href"))}"`;
if (["input", "button"].includes(tag) && el.hasAttribute("type")) line += ` type="${q(el.getAttribute("type"))}"`;
if (["input", "textarea"].includes(tag) && el.hasAttribute("placeholder")) line += ` placeholder="${q(el.getAttribute("placeholder"))}"`;
return line;
}
function optionLines(select, indent) {
return Array.from(select.options).map((o) => {
let line = `${indent}option "${q(clean(o.textContent))}"`;
if (o.selected) line += " (selected)";
if (o.hasAttribute("value")) line += ` value="${q(o.getAttribute("value"))}"`;
return line;
});
}
function generateAccessibilityTree(options = {}) {
const filter = options.filter === "interactive" ? "interactive" : "all";
const maxDepth = Number(options.depth) > 0 ? Number(options.depth) : 15;
const maxChars = Number(options.max_chars) > 0 ? Number(options.max_chars) : 50000;
const lines = [];
function children(el) {
const out = [...(el.shadowRoot?.children || []), ...el.children];
if (el.tagName === "IFRAME") {
try {
if (el.contentDocument?.body) out.push(...el.contentDocument.body.children);
} catch {}
}
return out;
}
function walk(el, depth, indent) {
if (!el || el.nodeType !== 1 || depth > maxDepth) return;
const tag = el.tagName.toLowerCase();
if (SKIP_TAGS.has(tag) || (tag === "input" && str(el.type).toLowerCase() === "hidden")) return;
const role = getRole(el);
if (filter === "interactive") {
if (INTERACTIVE_ROLES.has(role) && isVisible(el) && inViewport(el)) {
lines.push(describeLine(el, role, getAccessibleName(el, role)));
if (tag === "select") lines.push(...optionLines(el, " "));
}
if (tag !== "select") for (const c of children(el)) walk(c, depth + 1, indent);
return;
}
const name = getAccessibleName(el, role);
const shown = role !== "generic" || !!name;
if (shown) lines.push(indent + describeLine(el, role, name));
const next = shown ? indent + " " : indent;
if (tag === "select") {
lines.push(...optionLines(el, next));
if (el.multiple) return;
}
for (const c of children(el)) walk(c, depth + 1, next);
}
if (options.ref_id) {
const root = resolveRef(options.ref_id);
if (!root) return { error: `No element found with reference: "${options.ref_id}". The element may have been removed from the page.` };
walk(root, 1, "");
} else {
for (const c of (document.body || document.documentElement).children) walk(c, 1, "");
}
const full = lines.join("\n");
if (full.length <= maxChars) return { tree: full };
// Cut at a line boundary and say how much was left out.
let cut = full.lastIndexOf("\n", maxChars);
if (cut <= 0) cut = maxChars;
return {
tree:
full.slice(0, cut) +
`\n\n[Output truncated: showing ${cut} of ${full.length} characters. Pass a larger max_chars, ` +
`or use depth/ref_id (or filter: "interactive") to focus on part of the page.]`
};
}
// --- get_page_text ---
function getPageText() {
const candidates = ["article", "main", '[role="main"]', '[itemprop="articleBody"]', '[class*="article-body"]', '[class*="post-content"]', '[class*="entry-content"]', "#content", ".content"];
let source = null;
for (const sel of candidates) {
const el = document.querySelector(sel);
if (el && clean(el.innerText || "").length > 200) {
source = el;
break;
}
}
if (!source) source = document.body;
const text = (source.innerText || source.textContent || "")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
return { title: document.title || "", url: location.href, sourceTag: source.tagName.toLowerCase(), text: text.slice(0, 200000) };
}
// --- find ---
const STOP = new Set(["the", "a", "an", "of", "on", "in", "to", "for", "with", "and", "or", "that", "which", "is", "this", "page", "element", "containing", "contains", "named", "called", "labeled", "labelled", "text", "says", "saying", "at", "top", "bottom", "near"]);
const ROLE_WORDS = {
button: ["button"], btn: ["button"], link: ["link"], links: ["link"],
input: ["textbox", "searchbox", "combobox", "spinbutton"], field: ["textbox", "searchbox", "combobox", "spinbutton"],
textbox: ["textbox", "searchbox"], textarea: ["textbox"], box: ["textbox", "searchbox", "combobox", "checkbox"],
bar: ["textbox", "searchbox", "navigation", "toolbar"], checkbox: ["checkbox", "switch"], toggle: ["switch", "checkbox", "button"],
switch: ["switch", "checkbox"], radio: ["radio"], dropdown: ["combobox", "listbox", "button"], select: ["combobox", "listbox"],
menu: ["menu", "menubar", "menuitem", "button", "navigation"], tab: ["tab"], tabs: ["tab", "tablist"],
image: ["image"], img: ["image"], icon: ["image", "button", "link"], logo: ["image", "link"], picture: ["image"], photo: ["image"],
heading: ["heading"], header: ["heading", "banner"], title: ["heading"], dialog: ["dialog"], modal: ["dialog"],
popup: ["dialog", "menu"], slider: ["slider"], list: ["list", "listbox"], item: ["listitem", "option", "menuitem"],
option: ["option"], row: ["row"], table: ["table"], form: ["form"], navigation: ["navigation"], nav: ["navigation"],
video: ["video"], searchbar: ["searchbox", "textbox"]
};
function tokens(s) {
return String(s || "")
.toLowerCase()
.replace(/([a-z])([A-Z])/g, "$1 $2")
.split(/[^\p{L}\p{N}]+/u)
.filter(Boolean);
}
function collectAll(root, out = []) {
for (const el of root.querySelectorAll("*")) {
out.push(el);
if (el.shadowRoot) collectAll(el.shadowRoot, out);
}
return out;
}
function findElements(query) {
// Refs are handed out in page order, as the official extension's find
// does (it reads the whole tree first, starting with <body>).
if (document.body) getOrAssignRef(document.body);
generateAccessibilityTree({ filter: "all" });
const qTokens = tokens(query);
const roleHints = new Set();
const content = [];
for (const t of qTokens) {
if (ROLE_WORDS[t]) ROLE_WORDS[t].forEach((r) => roleHints.add(r));
if (!STOP.has(t)) content.push(t);
}
// Words that only name a role ("button") shouldn't also have to appear in
// the element's text, but they count when they do ("Search" button).
const contentOnly = content.filter((t) => !ROLE_WORDS[t]);
const phrase = clean(String(query).toLowerCase());
const scored = [];
for (const el of collectAll(document)) {
const tag = el.tagName.toLowerCase();
if (["script", "style", "noscript", "template", "head", "meta", "link", "html", "body", "br"].includes(tag)) continue;
// Hidden file inputs are the usual kind (a styled button opens them),
// and file_upload needs their ref, so they stay findable.
const hiddenFileInput = tag === "input" && str(el.type).toLowerCase() === "file";
if (!hiddenFileInput && !isVisible(el)) continue;
const role = getRole(el);
const name = getAccessibleName(el, role);
const interactive = isInteractive(el);
// Text is only a fair signal for small elements: a big container
// "contains" everything below it and would always win.
const rawText = clean(el.innerText || "");
const ownText = rawText.length <= 160 ? rawText : "";
const fields = {
name: tokens(name),
hint: tokens([str(el.placeholder), el.getAttribute("aria-label"), str(el.title), str(el.alt), el.getAttribute("aria-placeholder")].join(" ")),
attrs: tokens([el.id, typeof el.className === "string" ? el.className : "", el.getAttribute("name"), el.getAttribute("data-testid"), str(el.type), tag].join(" ")),
text: tokens(ownText),
value: tokens(tag === "input" || tag === "textarea" ? str(el.value) : "")
};
let score = 0;
let matched = 0;
for (const t of content) {
const hit = (arr) => arr.some((w) => w === t || (t.length > 3 && w.startsWith(t)) || (w.length > 3 && t.startsWith(w)));
let s = 0;
if (hit(fields.name)) s = 3;
else if (hit(fields.hint)) s = 2.5;
else if (hit(fields.text)) s = 2;
else if (hit(fields.value)) s = 1.5;
else if (hit(fields.attrs)) s = 1;
if (s) matched++;
score += s;
}
const roleMatch = roleHints.size > 0 && (roleHints.has(role) || (roleHints.has("textbox") && ["input", "textarea"].includes(tag)));
if (contentOnly.length && !contentOnly.some((t) => [...fields.name, ...fields.hint, ...fields.text, ...fields.value, ...fields.attrs].some((w) => w === t || (t.length > 3 && w.startsWith(t)) || (w.length > 3 && t.startsWith(w))))) continue;
if (!matched && !roleMatch) continue;
if (roleMatch) score += 3;
else if (roleHints.size) score -= 1.5;
if (interactive) score += 1;
if (phrase.length > 2 && (name.toLowerCase().includes(phrase) || ownText.toLowerCase().includes(phrase))) score += 3;
if (content.length) score *= 0.5 + 0.5 * (matched / content.length);
if (score <= 0.5) continue;
scored.push({ el, score, role, name, text: ownText });
}
// A match whose best signal came from text is usually also matched by
// its wrapper; keep the innermost one.
scored.sort((a, b) => b.score - a.score);
// Nested matches: a wrapper whose visible text is the same as its
// child's is the same thing on screen, and the child is the precise
// target (the wrapper's centre can be empty space). Otherwise keep the
// better-scoring one unless the two score about the same.
const kept = [];
for (const s of scored) {
const i = kept.findIndex((k) => k.el.contains(s.el) || s.el.contains(k.el));
if (i === -1) {
kept.push(s);
continue;
}
const k = kept[i];
const inner = k.el.contains(s.el) ? s : k;
const outer = inner === s ? k : s;
if (inner.text && inner.text === outer.text) {
kept[i] = { ...inner, score: Math.max(k.score, s.score) };
} else if (Math.abs(k.score - s.score) >= 1.5) {
kept.push(s);
}
}
kept.sort((a, b) => b.score - a.score);
// A <label> adds nothing when the control it labels is already listed.
for (let i = kept.length - 1; i >= 0; i--) {
const ctrl = kept[i].el.tagName === "LABEL" && kept[i].el.control;
if (ctrl && kept.some((k) => k.el === ctrl)) kept.splice(i, 1);
}
const total = kept.length;
const results = kept.slice(0, 20).map(({ el, role, name }) => ({
ref: getOrAssignRef(el),
role,
name,
type: el.tagName === "INPUT" ? str(el.type).toLowerCase() : null,
label: el.labels?.[0] ? clean(el.labels[0].textContent) : null
}));
return { results, total };
}
// --- form_input ---
function findInputInside(el) {
const tag = el.tagName.toLowerCase();
if (["input", "textarea", "select"].includes(tag) || el.isContentEditable) return el;
const root = el.shadowRoot || el;
const inner = root.querySelector("input, textarea, select, [contenteditable='true']");
if (inner) return inner;
for (const child of root.querySelectorAll("*")) {
const deep = child.shadowRoot?.querySelector("input, textarea, select");
if (deep) return deep;
}
return null;
}
// Messages follow the official extension's wording.
function setFormValue(ref, value) {
const el = resolveRef(ref);
if (!el) return { error: `No element found with reference: "${ref}". The element may have been removed from the page.` };
try {
el.scrollIntoView({ block: "center", behavior: "instant" });
} catch {}
const target = el.tagName === "BUTTON" ? el : findInputInside(el) || el;
const tag = target.tagName.toLowerCase();
const type = str(target.type).toLowerCase();
const fire = () => {
target.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
target.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
};
if (tag === "select") {
const want = String(value);
const opts = Array.from(target.options);
const opt = opts.find((o) => o.value === want) || opts.find((o) => clean(o.textContent) === want) ||
opts.find((o) => clean(o.textContent).toLowerCase() === want.toLowerCase());
if (!opt) {
return { error: `Option "${want}" not found. Available options: ${opts.map((o) => `"${clean(o.textContent)}" (value: "${o.value}")`).join(", ")}` };
}
const previous = target.value;
target.value = opt.value;
fire();
return { message: `Selected option "${opt.value}" in dropdown (previous: "${previous}")` };
}
if (tag === "input" && type === "checkbox") {
const previous = target.checked;
const shouldCheck = typeof value === "boolean" ? value : String(value).toLowerCase() === "true";
if (target.checked !== shouldCheck) target.click();
return { message: `Checkbox ${target.checked ? "checked" : "unchecked"} (previous: ${previous})` };
}
if (tag === "input" && type === "radio") {
const shouldCheck = typeof value === "boolean" ? value : String(value).toLowerCase() !== "false";
if (shouldCheck && !target.checked) target.click();
return { message: "ok" };
}
if (tag === "input" && type === "file") return { error: `Element type "INPUT" (file) is not a supported form input; use file_upload` };
if (tag === "input" || tag === "textarea") {
const previous = target.value;
target.focus();
const proto = tag === "textarea" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
if (setter) setter.call(target, String(value));
else target.value = String(value);
fire();
if (type === "range") return { message: "ok" };
return { message: `Set ${tag === "textarea" ? "textarea" : type || "text"} value to "${target.value}" (previous: "${previous}")` };
}
if (target.isContentEditable) {
const previous = target.textContent;
target.focus();
target.textContent = String(value);
fire();
return { message: `Set contenteditable value to "${target.textContent}" (previous: "${previous}")` };
}
return { error: `Element type "${target.tagName}" is not a supported form input` };
}
// --- geometry ---
function describeBrief(el) {
const id = el.id ? `#${el.id}` : "";
const cls = typeof el.className === "string" && el.className.trim() ? "." + el.className.trim().split(/\s+/)[0] : "";
const t = clean(el.textContent || "").slice(0, 40);
return `<${el.tagName.toLowerCase()}${id}${cls}>${t ? ` "${t}"` : ""}`;
}
// Centre of a ref'd element, scrolled into view first (a person scrolls
// before clicking, and an off-screen point can't be clicked at all).
function getRefCoordinates(ref, scroll = true) {
const el = resolveRef(ref);
if (!el) return null;
if (scroll) {
const r = el.getBoundingClientRect();
if (r.left < 0 || r.top < 0 || r.right > innerWidth || r.bottom > innerHeight) {
try {
el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
} catch {
el.scrollIntoView(true);
}
}
}
const r = el.getBoundingClientRect();
const x = Math.round(r.x + r.width / 2);
const y = Math.round(r.y + r.height / 2);
const reachable = x >= 0 && y >= 0 && x < innerWidth && y < innerHeight;
let covering = null;
if (reachable) {
const at = document.elementFromPoint(x, y);
if (at && at !== el && !el.contains(at) && !at.contains(el)) covering = describeBrief(at);
}
return { x, y, reachable, covering };
}
// --- agent overlay ---
// Same look as the official extension's: a pulsing orange glow around the
// viewport and an orange "phantom" cursor that glides to where the agent
// acts. Unlike the official one it is not touched for screenshots (that
// made the glow blink). Closed shadow root: page CSS can't touch it, and
// pointer-events:none keeps it out of input and hit tests.
const GLOW = "217, 119, 87";
const CURSOR_MS = 180;
const ARROW = "M0 0 L0 18 L4.5 14 L7.5 21.5 L11 20 L8 13 L14 13 Z";
let overlayHost = null;
let overlayParts = null;
let cursorPos = null;
function ensureOverlay() {
if (overlayHost?.isConnected) return overlayParts;
overlayHost = document.createElement("ocb-agent-overlay");
overlayHost.style.cssText = "all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483646;";
const root = overlayHost.attachShadow({ mode: "closed" });
root.innerHTML = `
<style>
@keyframes pulse { 0%, 100% { opacity: .6; } 50% { opacity: 1; } }
.glow { position: fixed; inset: 0; pointer-events: none; opacity: 0; transition: opacity .3s ease-in-out; }
.glow-inner { position: absolute; inset: 0; will-change: opacity; animation: pulse 2s ease-in-out infinite;
box-shadow: rgba(${GLOW}, .7) 0 0 15px inset, rgba(${GLOW}, .5) 0 0 25px inset, rgba(${GLOW}, .2) 0 0 35px inset; }
@media (prefers-reduced-motion: reduce) { .glow-inner { animation: none; } }
.cursor { position: fixed; top: 0; left: 0; pointer-events: none; will-change: transform;
transition: transform ${CURSOR_MS}ms cubic-bezier(.2, 0, 0, 1); }
.cursor svg { position: absolute; top: 0; left: 0; overflow: visible; }
.styled { filter: drop-shadow(rgba(${GLOW}, .9) 0 0 4px) drop-shadow(rgba(${GLOW}, .45) 0 0 10px); }
</style>
<div>
<div class="glow"><div class="glow-inner"></div></div>
<div class="cursor" aria-hidden="true">
<svg class="styled" width="20" height="26" viewBox="0 0 20 26">
<path d="${ARROW}" stroke="#D97757" stroke-width="3" stroke-linejoin="round" fill="#D97757"/>
<path d="${ARROW}" fill="#FAF9F5"/>
</svg>
</div>
</div>`;
overlayParts = { glow: root.querySelector(".glow"), cursor: root.querySelector(".cursor") };
(document.documentElement || document.body).appendChild(overlayHost);
// A new page starts with the cursor in the middle of the viewport.
cursorPos ??= { x: Math.round(innerWidth / 2), y: Math.round(innerHeight / 2) };
placeCursor(cursorPos.x, cursorPos.y, false);
return overlayParts;
}
function placeCursor(x, y, animate) {
const { cursor } = overlayParts;
cursor.style.transition = animate ? "" : "none";
cursor.style.transform = `translate3d(${x}px, ${y}px, 0)`;
cursorPos = { x, y };
}
const overlay = {
// The agent is working in this tab: glow on, cursor shown. It stays until
// the session ends.
active() {
const p = ensureOverlay();
p.glow.style.opacity = "1";
return { ok: true };
},
off() {
overlayHost?.remove();
overlayHost = null;
overlayParts = null;
return { ok: true };
},
// Glide the cursor to (x, y) and resolve once it has arrived, so the
// input the worker dispatches next lands as the cursor gets there.
async move(m) {
const p = overlay.active() && overlayParts;
const dist = Math.hypot(m.x - cursorPos.x, m.y - cursorPos.y);
placeCursor(m.x, m.y, true);
if (dist > 1) await new Promise((r) => setTimeout(r, CURSOR_MS));
return { ok: !!p };
}
};
// --- messages ---
const handlers = {
overlay: (m) => (overlay[m.op] ? overlay[m.op](m) : { ok: false }),
readPage: (m) => generateAccessibilityTree(m.options || {}),
getPageText: () => getPageText(),
find: (m) => findElements(m.query || ""),
setFormValue: (m) => setFormValue(m.ref, m.value),
refCoordinates: (m) => getRefCoordinates(m.ref, m.scroll !== false),
scrollToRef: (m) => {
const el = resolveRef(m.ref);
if (!el) return { ok: false };
el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
return { ok: true, desc: describeBrief(el) };
},
// Stamp a DOM attribute on a ref'd element so the worker can find it via
// CDP (which runs in the main world and can't see this world's refs).
markElement: (m) => {
const el = resolveRef(m.ref);
if (!el) return { ok: false };
document.querySelectorAll("[data-ocb-target]").forEach((e) => e.removeAttribute("data-ocb-target"));
el.setAttribute("data-ocb-target", "1");
return {
ok: true,
tag: el.tagName.toLowerCase(),
isFileInput: el.tagName.toLowerCase() === "input" && str(el.type).toLowerCase() === "file"
};
},
unmarkElement: () => {
document.querySelectorAll("[data-ocb-target]").forEach((e) => e.removeAttribute("data-ocb-target"));
return { ok: true };
}
};
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
const h = msg && msg.__ocb && handlers[msg.type];
if (!h) return false;
Promise.resolve()
.then(() => h(msg))
.then(
(result) => sendResponse({ result }),
(e) => sendResponse({ error: String(e && e.message) })
);
return true;
});
})();