Files
Firefox-MCP-extension/extension/content.js
T

302 lines
8.0 KiB
JavaScript

/*
* Firefox MCP Bridge - Content Script
*
* Runs in the context of web pages. Provides DOM-level access
* to the background script via browser.runtime.onMessage.
*/
let mcpIdCounter = 0;
// ------------------------------------------------------------------
// Element indexing helpers
// ------------------------------------------------------------------
function getNextId() {
return ++mcpIdCounter;
}
function isInteractiveElement(el) {
const tag = el.tagName.toLowerCase();
const interactiveTags = [
"button",
"a",
"input",
"select",
"textarea",
];
if (interactiveTags.includes(tag)) return true;
const role = el.getAttribute("role");
if (role === "button" || role === "link" || role === "checkbox" || role === "radio" || role === "switch") {
return true;
}
if (el.onclick || el.getAttribute("onclick")) return true;
if (el.isContentEditable) return true;
return false;
}
function getBasicInfo(el) {
const tag = el.tagName.toLowerCase();
const ariaRole = el.getAttribute("role");
const role = ariaRole || tag;
let text = "";
if (tag === "input") {
text = el.value || el.getAttribute("placeholder") || el.getAttribute("type") || "";
} else if (tag === "img") {
text = el.alt || el.getAttribute("src") || "";
} else {
const tc = el.textContent || el.innerText || "";
text = tc.trim().substring(0, 200);
}
const label =
el.getAttribute("aria-label") ||
el.getAttribute("alt") ||
el.getAttribute("title") ||
"";
const href = el.href || "";
const src = el.src || "";
return {
role: role,
text: text,
label: label,
tag: tag,
type: el.type || "",
name: el.name || "",
id_attr: el.id || "",
class: el.className || "",
href: href,
src: src,
};
}
function scanPage() {
const elements = [];
const selector =
"button, a, input, select, textarea, " +
"[role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch'], " +
"[onclick], [contenteditable='true']";
const interactive = document.querySelectorAll(selector);
interactive.forEach((el) => {
// Assign a stable mcp-id if not already present
let mcpId = el.getAttribute("data-mcp-id");
if (!mcpId) {
mcpId = getNextId().toString();
el.setAttribute("data-mcp-id", mcpId);
}
const info = getBasicInfo(el);
info.id = parseInt(mcpId, 10);
elements.push(info);
});
return elements;
}
function getElementByMcpId(id) {
return document.querySelector(`[data-mcp-id="${id}"]`);
}
function getElementDetails(id) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found in the DOM`);
}
const rect = el.getBoundingClientRect();
const computed = window.getComputedStyle(el);
const attributes = {};
for (let i = 0; i < el.attributes.length; i++) {
const attr = el.attributes[i];
attributes[attr.name] = attr.value;
}
return {
id: parseInt(el.getAttribute("data-mcp-id"), 10),
tag: el.tagName.toLowerCase(),
text: el.textContent ? el.textContent.trim() : "",
value: el.value || "",
html: el.outerHTML.substring(0, 2000),
attributes: attributes,
bounding_box: {
x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.round(rect.width),
height: Math.round(rect.height),
},
visible: computed.visibility !== "hidden" && computed.display !== "none",
disabled: el.disabled === true,
readonly: el.readOnly === true,
};
}
// ------------------------------------------------------------------
// Action implementations
// ------------------------------------------------------------------
function clickElement(id) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found`);
}
el.click();
return { success: true };
}
function typeText(id, text) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found`);
}
el.focus();
if (el.isContentEditable) {
// For contenteditable elements, try to replace the content using a selection and execCommand
// This is more likely to trigger framework state updates (like in Slate.js or Draft.js)
try {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('insertText', false, text);
} catch (e) {
// Fallback to innerText if execCommand fails
el.innerText = text;
}
} else {
// Standard input/textarea
el.value = text;
}
// Dispatch input and change events so frameworks (React, Vue, etc.) notice
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
return { success: true };
}
function pressKey(key) {
const active = document.activeElement || document.body;
const event = new KeyboardEvent("keydown", {
key: key,
code: key,
bubbles: true,
cancelable: true,
});
active.dispatchEvent(event);
return { success: true };
}
function scrollPage(direction, amount) {
let pixels = amount;
if (amount > 0 && amount <= 100) {
// Treat as percentage of viewport
const viewportSize =
direction === "up" || direction === "down"
? window.innerHeight
: window.innerWidth;
pixels = (amount / 100) * viewportSize;
}
if (direction === "up") {
window.scrollBy(0, -pixels);
} else if (direction === "down") {
window.scrollBy(0, pixels);
} else if (direction === "left") {
window.scrollBy(-pixels, 0);
} else if (direction === "right") {
window.scrollBy(pixels, 0);
}
return { success: true };
}
function executeScript(jsCode) {
try {
const result = window.eval(jsCode);
return {
result: result !== undefined ? String(result) : "",
};
} catch (err) {
throw new Error(`Script error: ${err.message}`);
}
}
function readPageText() {
// Build a "reader mode" version by cloning the document and stripping noise
const clone = document.cloneNode(true);
const removeTags = [
"script",
"style",
"nav",
"header",
"footer",
"aside",
"iframe",
"noscript",
];
removeTags.forEach((tag) => {
clone.querySelectorAll(tag).forEach((el) => el.remove());
});
let text = clone.textContent || clone.innerText || "";
// Normalize whitespace
text = text.replace(/\n\s*\n/g, "\n").replace(/\s+/g, " ").trim();
return text.substring(0, 10000); // Cap size for token budget
}
// ------------------------------------------------------------------
// Message listener: receives requests from the background script
// ------------------------------------------------------------------
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type !== "mcp_call") {
return;
}
(async () => {
try {
let result;
switch (message.function) {
case "getPageSummary":
result = scanPage();
break;
case "getElementDetails":
result = getElementDetails(message.args.id);
break;
case "clickElement":
result = clickElement(message.args.id);
break;
case "typeText":
result = typeText(message.args.id, message.args.text);
break;
case "pressKey":
result = pressKey(message.args.key);
break;
case "scrollPage":
result = scrollPage(message.args.direction, message.args.amount);
break;
case "executeScript":
result = executeScript(message.args.js_code);
break;
case "readPageText":
result = readPageText();
break;
default:
throw new Error(`Unknown content function: ${message.function}`);
}
sendResponse({ result: result });
} catch (err) {
sendResponse({ error: err.message });
}
})();
return true; // Keep the message channel open for async response
});