claude-chrome-android 1.3.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claude-code-bridge.crx +0 -0
- package/dist/cli.js +278 -164
- package/dist/edge-claude-ext/background.js +1492 -0
- package/dist/edge-claude-ext/content.js +1044 -0
- package/dist/edge-claude-ext/icon128.png +0 -0
- package/dist/edge-claude-ext/icon16.png +0 -0
- package/dist/edge-claude-ext/icon48.png +0 -0
- package/dist/edge-claude-ext/launcher.html +63 -0
- package/dist/edge-claude-ext/launcher.js +98 -0
- package/dist/edge-claude-ext/manifest.json +35 -0
- package/dist/edge-claude-ext/popup.html +444 -0
- package/dist/edge-claude-ext/popup.js +637 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1044 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code Browser Bridge — Content Script
|
|
3
|
+
*
|
|
4
|
+
* Injected into every page. Handles DOM reading, element interaction,
|
|
5
|
+
* accessibility tree generation, and form input for Claude Code tools.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// --- Ref ID tracking ---------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
/** @type {Map<string, Element>} */
|
|
11
|
+
const refMap = new Map();
|
|
12
|
+
/** Reverse index: Element → ref string for O(1) lookup (WeakMap avoids memory leaks) */
|
|
13
|
+
const refReverseMap = new WeakMap();
|
|
14
|
+
let refCounter = 0;
|
|
15
|
+
|
|
16
|
+
function getOrCreateRef(el) {
|
|
17
|
+
// O(1) reverse lookup instead of O(n) refMap scan
|
|
18
|
+
const existing = refReverseMap.get(el);
|
|
19
|
+
if (existing && refMap.has(existing)) return existing;
|
|
20
|
+
const ref = `ref_${++refCounter}`;
|
|
21
|
+
refMap.set(ref, el);
|
|
22
|
+
refReverseMap.set(el, ref);
|
|
23
|
+
return ref;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolveRef(refId) {
|
|
27
|
+
const el = refMap.get(refId);
|
|
28
|
+
if (el && !el.isConnected) {
|
|
29
|
+
refMap.delete(refId);
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return el || null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Prune refs to elements no longer in the DOM (SPA navigations, removed nodes) */
|
|
36
|
+
function pruneDeadRefs() {
|
|
37
|
+
for (const [ref, el] of refMap.entries()) {
|
|
38
|
+
if (!el.isConnected) refMap.delete(ref);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// --- Console capture ---------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
const capturedConsole = [];
|
|
45
|
+
const MAX_CONSOLE_MESSAGES = 50;
|
|
46
|
+
|
|
47
|
+
// Intercept console methods
|
|
48
|
+
["log", "warn", "error", "info", "debug"].forEach((method) => {
|
|
49
|
+
const original = console[method];
|
|
50
|
+
console[method] = function (...args) {
|
|
51
|
+
capturedConsole.push({
|
|
52
|
+
level: method,
|
|
53
|
+
message: args.map((a) => {
|
|
54
|
+
try { return typeof a === "string" ? a : JSON.stringify(a); }
|
|
55
|
+
catch { return String(a); }
|
|
56
|
+
}).join(" "),
|
|
57
|
+
timestamp: Date.now(),
|
|
58
|
+
});
|
|
59
|
+
if (capturedConsole.length > MAX_CONSOLE_MESSAGES) {
|
|
60
|
+
capturedConsole.shift();
|
|
61
|
+
}
|
|
62
|
+
original.apply(console, args);
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// --- Message handler ---------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
// --- Persistent port for reliable messaging on Android Edge ------------------
|
|
69
|
+
// chrome.runtime.onMessage + sendResponse is unreliable on Android Edge:
|
|
70
|
+
// message ports corrupt after 2-3 calls. Use chrome.runtime.connect for a
|
|
71
|
+
// persistent port that stays open across multiple tool calls.
|
|
72
|
+
|
|
73
|
+
let port = null;
|
|
74
|
+
let portReconnectAttempts = 0;
|
|
75
|
+
|
|
76
|
+
function connectPort() {
|
|
77
|
+
try {
|
|
78
|
+
port = chrome.runtime.connect({ name: "cfc-content" });
|
|
79
|
+
} catch {
|
|
80
|
+
// Extension context invalidated — stop retrying
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Reset backoff after connection survives 1s without disconnecting.
|
|
85
|
+
// This handles both initial connect and reconnects after failures.
|
|
86
|
+
const connectTimer = setTimeout(() => {
|
|
87
|
+
portReconnectAttempts = 0;
|
|
88
|
+
}, 1000);
|
|
89
|
+
|
|
90
|
+
port.onMessage.addListener((msg) => {
|
|
91
|
+
if (!msg.action || !msg._reqId) return;
|
|
92
|
+
// Decouple from port message handler to avoid blocking
|
|
93
|
+
setTimeout(() => {
|
|
94
|
+
handleAction(msg.action, msg.params || {})
|
|
95
|
+
.then((result) => {
|
|
96
|
+
try { port.postMessage({ _reqId: msg._reqId, result }); } catch {}
|
|
97
|
+
})
|
|
98
|
+
.catch((err) => {
|
|
99
|
+
try { port.postMessage({ _reqId: msg._reqId, result: { error: err.message || String(err) } }); } catch {}
|
|
100
|
+
});
|
|
101
|
+
}, 0);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
port.onDisconnect.addListener(() => {
|
|
105
|
+
clearTimeout(connectTimer); // connection didn't survive — don't reset backoff
|
|
106
|
+
port = null;
|
|
107
|
+
portReconnectAttempts++;
|
|
108
|
+
// Exponential backoff: 1s, 2s, 4s, 8s, ... capped at 60s
|
|
109
|
+
const delay = Math.min(1000 * Math.pow(2, portReconnectAttempts - 1), 60000);
|
|
110
|
+
setTimeout(() => {
|
|
111
|
+
try { connectPort(); } catch {}
|
|
112
|
+
}, delay);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
connectPort();
|
|
116
|
+
|
|
117
|
+
// Keep legacy onMessage as fallback for backward compatibility
|
|
118
|
+
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|
119
|
+
if (!msg.action) return;
|
|
120
|
+
setTimeout(() => {
|
|
121
|
+
handleAction(msg.action, msg.params || {})
|
|
122
|
+
.then((result) => { try { sendResponse(result); } catch {} })
|
|
123
|
+
.catch((err) => { try { sendResponse({ error: err.message || String(err) }); } catch {} });
|
|
124
|
+
}, 0);
|
|
125
|
+
return true;
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
async function handleAction(action, params) {
|
|
129
|
+
// Prune DOM refs detached by SPA navigations before tree-building operations
|
|
130
|
+
if (action === "read_page" || action === "find" || action === "get_page_text") {
|
|
131
|
+
pruneDeadRefs();
|
|
132
|
+
}
|
|
133
|
+
switch (action) {
|
|
134
|
+
case "read_page":
|
|
135
|
+
return readPage(params);
|
|
136
|
+
case "find":
|
|
137
|
+
return findElements(params);
|
|
138
|
+
case "form_input":
|
|
139
|
+
return formInput(params);
|
|
140
|
+
case "javascript_exec":
|
|
141
|
+
return javascriptExec(params);
|
|
142
|
+
case "click":
|
|
143
|
+
return simulateClick(params);
|
|
144
|
+
case "type_text":
|
|
145
|
+
return typeText(params);
|
|
146
|
+
case "key_press":
|
|
147
|
+
return keyPress(params);
|
|
148
|
+
case "scroll":
|
|
149
|
+
return scroll(params);
|
|
150
|
+
case "scroll_to":
|
|
151
|
+
return scrollTo(params);
|
|
152
|
+
case "hover":
|
|
153
|
+
return simulateHover(params);
|
|
154
|
+
case "screenshot":
|
|
155
|
+
return takeScreenshot(params);
|
|
156
|
+
case "read_console":
|
|
157
|
+
return readConsole(params);
|
|
158
|
+
case "clear_console":
|
|
159
|
+
return clearConsole();
|
|
160
|
+
case "get_storage":
|
|
161
|
+
return getStorage();
|
|
162
|
+
case "delete_storage_item":
|
|
163
|
+
return deleteStorageItem(params);
|
|
164
|
+
case "get_page_text":
|
|
165
|
+
return getPageText(params);
|
|
166
|
+
case "drag":
|
|
167
|
+
return simulateDrag(params);
|
|
168
|
+
case "get_viewport_dims":
|
|
169
|
+
return { width: window.innerWidth, height: window.innerHeight };
|
|
170
|
+
case "upload_image":
|
|
171
|
+
return uploadImage(params);
|
|
172
|
+
default:
|
|
173
|
+
return { error: `Unknown action: ${action}` };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// --- read_page: Accessibility tree -------------------------------------------
|
|
178
|
+
|
|
179
|
+
function readPage(params) {
|
|
180
|
+
const { filter, depth, ref_id, max_chars } = params;
|
|
181
|
+
const maxDepth = depth || 15;
|
|
182
|
+
const maxChars = max_chars || 50000;
|
|
183
|
+
|
|
184
|
+
let root = document.body;
|
|
185
|
+
if (ref_id) {
|
|
186
|
+
const el = resolveRef(ref_id);
|
|
187
|
+
if (!el) return { error: `Element ${ref_id} not found` };
|
|
188
|
+
root = el;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Node count limit prevents O(n²) getComputedStyle calls on massive DOMs
|
|
192
|
+
let nodeCount = 0;
|
|
193
|
+
const MAX_NODES = 3000;
|
|
194
|
+
const tree = buildAccessibilityTree(root, 0, maxDepth, filter === "interactive", () => ++nodeCount > MAX_NODES);
|
|
195
|
+
let output = serializeTree(tree, 0);
|
|
196
|
+
|
|
197
|
+
if (output.length > maxChars) {
|
|
198
|
+
output = output.slice(0, maxChars);
|
|
199
|
+
output += "\n... [TRUNCATED — use depth or ref_id to narrow scope]";
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return { result: output };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function buildAccessibilityTree(el, currentDepth, maxDepth, interactiveOnly, isOverLimit) {
|
|
206
|
+
if (currentDepth > maxDepth) return null;
|
|
207
|
+
if (!el || el.nodeType !== Node.ELEMENT_NODE) return null;
|
|
208
|
+
if (isOverLimit && isOverLimit()) return null;
|
|
209
|
+
|
|
210
|
+
const tag = el.tagName?.toLowerCase() || "";
|
|
211
|
+
|
|
212
|
+
// Skip hidden elements
|
|
213
|
+
if (tag === "script" || tag === "style" || tag === "noscript") return null;
|
|
214
|
+
const style = window.getComputedStyle(el);
|
|
215
|
+
if (style.display === "none" || style.visibility === "hidden") return null;
|
|
216
|
+
|
|
217
|
+
const role = el.getAttribute("role") || getImplicitRole(tag);
|
|
218
|
+
const isInteractive = isInteractiveElement(el, tag, role);
|
|
219
|
+
|
|
220
|
+
// If filtering for interactive only, skip non-interactive elements (but still traverse children)
|
|
221
|
+
const includeThis = !interactiveOnly || isInteractive;
|
|
222
|
+
|
|
223
|
+
const node = {
|
|
224
|
+
ref: includeThis ? getOrCreateRef(el) : null,
|
|
225
|
+
tag,
|
|
226
|
+
role,
|
|
227
|
+
text: getDirectText(el),
|
|
228
|
+
attributes: getRelevantAttributes(el),
|
|
229
|
+
interactive: isInteractive,
|
|
230
|
+
children: [],
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
for (const child of el.children) {
|
|
234
|
+
const childNode = buildAccessibilityTree(child, currentDepth + 1, maxDepth, interactiveOnly, isOverLimit);
|
|
235
|
+
if (childNode) {
|
|
236
|
+
node.children.push(childNode);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// If this node has nothing interesting and no children, skip it
|
|
241
|
+
if (!includeThis && node.children.length === 0) return null;
|
|
242
|
+
|
|
243
|
+
// If not included but has children, pass through children (flatten)
|
|
244
|
+
if (!includeThis && node.children.length > 0) {
|
|
245
|
+
// Return a virtual node that just holds children
|
|
246
|
+
return { ...node, passthrough: true };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return node;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function serializeTree(node, indent) {
|
|
253
|
+
if (!node) return "";
|
|
254
|
+
|
|
255
|
+
const lines = [];
|
|
256
|
+
const pad = " ".repeat(indent);
|
|
257
|
+
|
|
258
|
+
if (node.passthrough) {
|
|
259
|
+
// Flatten — just serialize children at same indent
|
|
260
|
+
for (const child of node.children) {
|
|
261
|
+
lines.push(serializeTree(child, indent));
|
|
262
|
+
}
|
|
263
|
+
return lines.join("");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
let line = `${pad}[${node.ref || "-"}] <${node.tag}>`;
|
|
267
|
+
if (node.role) line += ` role="${node.role}"`;
|
|
268
|
+
if (node.interactive) line += " (interactive)";
|
|
269
|
+
|
|
270
|
+
const attrs = node.attributes;
|
|
271
|
+
if (attrs.id) line += ` id="${attrs.id}"`;
|
|
272
|
+
if (attrs.class) line += ` class="${attrs.class}"`;
|
|
273
|
+
if (attrs.href) line += ` href="${attrs.href}"`;
|
|
274
|
+
if (attrs.src) line += ` src="${attrs.src}"`;
|
|
275
|
+
if (attrs.placeholder) line += ` placeholder="${attrs.placeholder}"`;
|
|
276
|
+
if (attrs.value !== undefined) line += ` value="${attrs.value}"`;
|
|
277
|
+
if (attrs.ariaLabel) line += ` aria-label="${attrs.ariaLabel}"`;
|
|
278
|
+
if (attrs.name) line += ` name="${attrs.name}"`;
|
|
279
|
+
if (attrs.type) line += ` type="${attrs.type}"`;
|
|
280
|
+
|
|
281
|
+
if (node.text) {
|
|
282
|
+
const text = node.text.length > 100 ? node.text.slice(0, 100) + "..." : node.text;
|
|
283
|
+
line += ` "${text}"`;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
lines.push(line + "\n");
|
|
287
|
+
|
|
288
|
+
for (const child of node.children) {
|
|
289
|
+
lines.push(serializeTree(child, indent + 1));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return lines.join("");
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function getImplicitRole(tag) {
|
|
296
|
+
const roleMap = {
|
|
297
|
+
a: "link", button: "button", input: "textbox", select: "combobox",
|
|
298
|
+
textarea: "textbox", img: "img", h1: "heading", h2: "heading",
|
|
299
|
+
h3: "heading", h4: "heading", h5: "heading", h6: "heading",
|
|
300
|
+
nav: "navigation", main: "main", aside: "complementary",
|
|
301
|
+
footer: "contentinfo", header: "banner", form: "form",
|
|
302
|
+
table: "table", ul: "list", ol: "list", li: "listitem",
|
|
303
|
+
};
|
|
304
|
+
return roleMap[tag] || "";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function isInteractiveElement(el, tag, role) {
|
|
308
|
+
const interactiveTags = ["a", "button", "input", "select", "textarea", "details", "summary"];
|
|
309
|
+
if (interactiveTags.includes(tag)) return true;
|
|
310
|
+
if (el.hasAttribute("onclick") || el.hasAttribute("tabindex")) return true;
|
|
311
|
+
if (el.getAttribute("contenteditable") === "true") return true;
|
|
312
|
+
const interactiveRoles = ["button", "link", "textbox", "combobox", "checkbox", "radio",
|
|
313
|
+
"slider", "switch", "tab", "menuitem", "option"];
|
|
314
|
+
return interactiveRoles.includes(role);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function getDirectText(el) {
|
|
318
|
+
let text = "";
|
|
319
|
+
for (const child of el.childNodes) {
|
|
320
|
+
if (child.nodeType === Node.TEXT_NODE) {
|
|
321
|
+
text += child.textContent;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return text.trim();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function getRelevantAttributes(el) {
|
|
328
|
+
const attrs = {};
|
|
329
|
+
const names = ["id", "class", "href", "src", "name", "type", "value",
|
|
330
|
+
"placeholder", "aria-label", "aria-labelledby", "aria-describedby",
|
|
331
|
+
"title", "alt", "role", "data-testid"];
|
|
332
|
+
for (const name of names) {
|
|
333
|
+
const val = el.getAttribute(name);
|
|
334
|
+
if (val) {
|
|
335
|
+
const key = name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
336
|
+
attrs[key] = val.length > 200 ? val.slice(0, 200) + "..." : val;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// Get value for form elements
|
|
340
|
+
if ("value" in el && el.value !== undefined) {
|
|
341
|
+
attrs.value = String(el.value).slice(0, 200);
|
|
342
|
+
}
|
|
343
|
+
return attrs;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// --- find: Element search ----------------------------------------------------
|
|
347
|
+
|
|
348
|
+
function findElements(params) {
|
|
349
|
+
const { query } = params;
|
|
350
|
+
const queryLower = query.toLowerCase();
|
|
351
|
+
const results = [];
|
|
352
|
+
const MAX_RESULTS = 20;
|
|
353
|
+
|
|
354
|
+
const allElements = document.querySelectorAll("*");
|
|
355
|
+
|
|
356
|
+
for (const el of allElements) {
|
|
357
|
+
if (results.length >= MAX_RESULTS) break;
|
|
358
|
+
|
|
359
|
+
const tag = el.tagName?.toLowerCase() || "";
|
|
360
|
+
if (tag === "script" || tag === "style" || tag === "noscript") continue;
|
|
361
|
+
|
|
362
|
+
const text = (el.textContent || "").toLowerCase();
|
|
363
|
+
const ariaLabel = (el.getAttribute("aria-label") || "").toLowerCase();
|
|
364
|
+
const placeholder = (el.getAttribute("placeholder") || "").toLowerCase();
|
|
365
|
+
const title = (el.getAttribute("title") || "").toLowerCase();
|
|
366
|
+
const role = (el.getAttribute("role") || getImplicitRole(tag)).toLowerCase();
|
|
367
|
+
const alt = (el.getAttribute("alt") || "").toLowerCase();
|
|
368
|
+
const name = (el.getAttribute("name") || "").toLowerCase();
|
|
369
|
+
const id = (el.getAttribute("id") || "").toLowerCase();
|
|
370
|
+
const className = (el.getAttribute("class") || "").toLowerCase();
|
|
371
|
+
|
|
372
|
+
// Score match quality
|
|
373
|
+
let score = 0;
|
|
374
|
+
if (ariaLabel.includes(queryLower)) score += 10;
|
|
375
|
+
if (placeholder.includes(queryLower)) score += 9;
|
|
376
|
+
if (title.includes(queryLower)) score += 8;
|
|
377
|
+
if (alt.includes(queryLower)) score += 8;
|
|
378
|
+
if (name.includes(queryLower)) score += 7;
|
|
379
|
+
if (id.includes(queryLower)) score += 6;
|
|
380
|
+
if (role.includes(queryLower)) score += 5;
|
|
381
|
+
if (className.includes(queryLower)) score += 3;
|
|
382
|
+
|
|
383
|
+
// Direct text match (only the node's own text, not children)
|
|
384
|
+
const directText = getDirectText(el).toLowerCase();
|
|
385
|
+
if (directText.includes(queryLower)) score += 10;
|
|
386
|
+
|
|
387
|
+
// Weaker: any child text
|
|
388
|
+
if (score === 0 && text.includes(queryLower)) score += 1;
|
|
389
|
+
|
|
390
|
+
if (score > 0) {
|
|
391
|
+
const ref = getOrCreateRef(el);
|
|
392
|
+
const rect = el.getBoundingClientRect();
|
|
393
|
+
results.push({
|
|
394
|
+
ref,
|
|
395
|
+
tag,
|
|
396
|
+
role: el.getAttribute("role") || getImplicitRole(tag),
|
|
397
|
+
text: getDirectText(el).slice(0, 100),
|
|
398
|
+
ariaLabel: el.getAttribute("aria-label") || "",
|
|
399
|
+
coordinates: { x: Math.round(rect.x + rect.width / 2), y: Math.round(rect.y + rect.height / 2) },
|
|
400
|
+
score,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Sort by score descending
|
|
406
|
+
results.sort((a, b) => b.score - a.score);
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
result: results,
|
|
410
|
+
totalMatches: results.length,
|
|
411
|
+
...(results.length >= MAX_RESULTS && { note: "Results limited to 20. Use a more specific query." }),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// --- form_input: Set form values ---------------------------------------------
|
|
416
|
+
|
|
417
|
+
function formInput(params) {
|
|
418
|
+
const { ref, value } = params;
|
|
419
|
+
const el = resolveRef(ref);
|
|
420
|
+
if (!el) return { error: `Element ${ref} not found` };
|
|
421
|
+
|
|
422
|
+
const tag = el.tagName?.toLowerCase();
|
|
423
|
+
|
|
424
|
+
if (tag === "select") {
|
|
425
|
+
el.value = value;
|
|
426
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
427
|
+
return { result: `Set select value to "${value}"` };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (tag === "input" && (el.type === "checkbox" || el.type === "radio")) {
|
|
431
|
+
el.checked = Boolean(value);
|
|
432
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
433
|
+
return { result: `Set ${el.type} to ${el.checked}` };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (tag === "input" || tag === "textarea") {
|
|
437
|
+
// Use native input setter to trigger React/Vue state updates
|
|
438
|
+
const nativeInputValueSetter =
|
|
439
|
+
Object.getOwnPropertyDescriptor(
|
|
440
|
+
tag === "textarea" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
|
|
441
|
+
"value"
|
|
442
|
+
)?.set;
|
|
443
|
+
|
|
444
|
+
if (nativeInputValueSetter) {
|
|
445
|
+
nativeInputValueSetter.call(el, value);
|
|
446
|
+
} else {
|
|
447
|
+
el.value = value;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
451
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
452
|
+
return { result: `Set input value to "${String(value).slice(0, 50)}"` };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// contenteditable
|
|
456
|
+
if (el.getAttribute("contenteditable") === "true") {
|
|
457
|
+
el.textContent = value;
|
|
458
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
459
|
+
return { result: `Set contenteditable value` };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return { error: `Element ${ref} (${tag}) is not a form input` };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// --- javascript_exec ---------------------------------------------------------
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Primary execution path: script-tag injection + window.postMessage bridge.
|
|
469
|
+
*
|
|
470
|
+
* chrome.tabs.executeScript runs in the ISOLATED world only (MV2), and
|
|
471
|
+
* chrome.scripting.executeScript(world:"MAIN") hangs indefinitely on Android
|
|
472
|
+
* Edge. But appending a <script> element with inline textContent executes
|
|
473
|
+
* synchronously in the page's MAIN world — this is a standard capability of
|
|
474
|
+
* content scripts that share DOM access with the page.
|
|
475
|
+
*
|
|
476
|
+
* Subject to the page's own CSP: pages that disallow inline script execution
|
|
477
|
+
* (strict 'script-src' without 'unsafe-inline') will silently block the
|
|
478
|
+
* injected script. The timeout below converts that silent block into an error.
|
|
479
|
+
*
|
|
480
|
+
* Return values must be structured-clone-able (primitives, plain objects,
|
|
481
|
+
* arrays). DOM nodes, functions, and cyclic structures cannot cross the
|
|
482
|
+
* postMessage boundary.
|
|
483
|
+
*
|
|
484
|
+
* Async code is supported: if the IIFE returns a thenable, we await it.
|
|
485
|
+
*/
|
|
486
|
+
const MAIN_WORLD_TIMEOUT_MS = 5000;
|
|
487
|
+
|
|
488
|
+
function executeInMainWorld(code) {
|
|
489
|
+
return new Promise((resolve, reject) => {
|
|
490
|
+
const id = (crypto?.randomUUID && crypto.randomUUID()) ||
|
|
491
|
+
`cfc-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
492
|
+
let settled = false;
|
|
493
|
+
let timeoutHandle;
|
|
494
|
+
|
|
495
|
+
function cleanup() {
|
|
496
|
+
window.removeEventListener("message", handler);
|
|
497
|
+
clearTimeout(timeoutHandle);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function handler(event) {
|
|
501
|
+
// Reject cross-origin messages and any message not addressed to us
|
|
502
|
+
if (event.source !== window) return;
|
|
503
|
+
const data = event.data;
|
|
504
|
+
if (!data || data.type !== "cfc-main-result" || data.id !== id) return;
|
|
505
|
+
if (settled) return;
|
|
506
|
+
settled = true;
|
|
507
|
+
cleanup();
|
|
508
|
+
if ("error" in data) reject(new Error(data.error));
|
|
509
|
+
else resolve(data.result);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
window.addEventListener("message", handler);
|
|
513
|
+
|
|
514
|
+
timeoutHandle = setTimeout(() => {
|
|
515
|
+
if (settled) return;
|
|
516
|
+
settled = true;
|
|
517
|
+
cleanup();
|
|
518
|
+
reject(new Error(
|
|
519
|
+
`executeInMainWorld timed out after ${MAIN_WORLD_TIMEOUT_MS}ms ` +
|
|
520
|
+
`(page CSP blocking inline script injection, or code hung without returning)`
|
|
521
|
+
));
|
|
522
|
+
}, MAIN_WORLD_TIMEOUT_MS);
|
|
523
|
+
|
|
524
|
+
// Inject the script tag. textContent runs synchronously in MAIN world.
|
|
525
|
+
//
|
|
526
|
+
// Execution semantics: we pass user code to eval() so that a bare
|
|
527
|
+
// expression returns its value (matching the tool's documented contract
|
|
528
|
+
// of "no return needed"). eval runs in the enclosing IIFE's scope, sees
|
|
529
|
+
// page globals (window, document, page-defined vars), and its completion
|
|
530
|
+
// value becomes our result. Promise-returning code is awaited.
|
|
531
|
+
//
|
|
532
|
+
// Build the injected source via string concatenation (NOT a template
|
|
533
|
+
// literal): user code may legitimately contain backticks or ${...}
|
|
534
|
+
// template syntax, which would terminate an outer template literal here
|
|
535
|
+
// at build time. JSON.stringify(code) produces a safely-escaped string
|
|
536
|
+
// literal we can hand to eval().
|
|
537
|
+
//
|
|
538
|
+
// Scripts created via document.createElement("script") + textContent
|
|
539
|
+
// are NOT subject to the </script>-terminator rule that applies to inline
|
|
540
|
+
// HTML script tags, so user code containing </script> strings is safe.
|
|
541
|
+
//
|
|
542
|
+
// CSP: pages with 'unsafe-inline' disallowed block the <script> injection
|
|
543
|
+
// entirely (timeout path). Pages with 'unsafe-eval' disallowed block the
|
|
544
|
+
// eval call specifically and the wrapper's try/catch reports the error.
|
|
545
|
+
const script = document.createElement("script");
|
|
546
|
+
script.textContent =
|
|
547
|
+
"(function() {" +
|
|
548
|
+
" var __cfc_id = " + JSON.stringify(id) + ";" +
|
|
549
|
+
" var __cfc_post = function(payload) {" +
|
|
550
|
+
" try {" +
|
|
551
|
+
" window.postMessage(Object.assign(" +
|
|
552
|
+
" { type: 'cfc-main-result', id: __cfc_id }, payload), '*');" +
|
|
553
|
+
" } catch (e) {" +
|
|
554
|
+
" window.postMessage({" +
|
|
555
|
+
" type: 'cfc-main-result', id: __cfc_id," +
|
|
556
|
+
" error: 'result not structured-clone-able: ' + (e && e.message || e)" +
|
|
557
|
+
" }, '*');" +
|
|
558
|
+
" }" +
|
|
559
|
+
" };" +
|
|
560
|
+
" try {" +
|
|
561
|
+
" var __cfc_r = (0, eval)(" + JSON.stringify(code) + ");" +
|
|
562
|
+
" if (__cfc_r && typeof __cfc_r.then === 'function') {" +
|
|
563
|
+
" __cfc_r.then(" +
|
|
564
|
+
" function(v) { __cfc_post({ result: v }); }," +
|
|
565
|
+
" function(e) { __cfc_post({ error: String(e && e.message || e) }); }" +
|
|
566
|
+
" );" +
|
|
567
|
+
" } else {" +
|
|
568
|
+
" __cfc_post({ result: __cfc_r });" +
|
|
569
|
+
" }" +
|
|
570
|
+
" } catch (e) {" +
|
|
571
|
+
" __cfc_post({ error: String(e && e.message || e) });" +
|
|
572
|
+
" }" +
|
|
573
|
+
"})();";
|
|
574
|
+
(document.head || document.documentElement).appendChild(script);
|
|
575
|
+
script.remove(); // remove tag immediately — script already ran
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Execute JavaScript in the page's MAIN world.
|
|
581
|
+
*
|
|
582
|
+
* Strategy: try MAIN-world injection first (works on most pages). If that
|
|
583
|
+
* times out (page CSP blocking, hung code) or throws, fall back to the
|
|
584
|
+
* restricted DOM-property evaluator so common simple queries still succeed
|
|
585
|
+
* even on strict-CSP pages.
|
|
586
|
+
*/
|
|
587
|
+
async function javascriptExec(params) {
|
|
588
|
+
const { code } = params;
|
|
589
|
+
const trimmed = code.trim();
|
|
590
|
+
|
|
591
|
+
// 1. Try MAIN world via script-tag injection (works on most pages)
|
|
592
|
+
let mainErrMsg = null;
|
|
593
|
+
try {
|
|
594
|
+
const result = await executeInMainWorld(code);
|
|
595
|
+
return { result: JSON.stringify(result) };
|
|
596
|
+
} catch (mainErr) {
|
|
597
|
+
// CSP blocked inline script, code threw, or timed out. Fall through to
|
|
598
|
+
// DOM-property evaluator so common read patterns still work on strict pages.
|
|
599
|
+
mainErrMsg = mainErr && mainErr.message ? mainErr.message : String(mainErr);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// 2. DOM-property fallback — restricted expression set, works under any CSP
|
|
603
|
+
try {
|
|
604
|
+
// Pattern: simple global properties
|
|
605
|
+
// document.title, document.URL, document.readyState, location.href, etc.
|
|
606
|
+
if (/^(document\.(title|URL|readyState|domain|referrer|characterSet|contentType|lastModified)|location\.(href|hostname|pathname|search|hash|origin|protocol|port))$/.test(trimmed)) {
|
|
607
|
+
const parts = trimmed.split(".");
|
|
608
|
+
let val = window;
|
|
609
|
+
for (const p of parts) val = val[p];
|
|
610
|
+
return { result: JSON.stringify(val) };
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// Pattern: document.getElementById('x').prop or document.querySelector('sel').prop
|
|
614
|
+
const READABLE_PROPS = "textContent|innerText|innerHTML|outerHTML|value|className|id|tagName|checked|disabled|href|src|alt|title|placeholder|type|name";
|
|
615
|
+
const elPropMatch = trimmed.match(
|
|
616
|
+
new RegExp(`^document\\.(getElementById|querySelector)\\(\\s*['"]([^'"]+)['"]\\s*\\)\\s*\\.\\s*(${READABLE_PROPS})$`)
|
|
617
|
+
);
|
|
618
|
+
if (elPropMatch) {
|
|
619
|
+
const [, method, selector, prop] = elPropMatch;
|
|
620
|
+
const el = method === "getElementById" ? document.getElementById(selector) : document.querySelector(selector);
|
|
621
|
+
if (!el) return { result: "null" };
|
|
622
|
+
return { result: JSON.stringify(el[prop]) };
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Pattern: document.querySelectorAll('sel').length
|
|
626
|
+
const qsaLenMatch = trimmed.match(/^document\.querySelectorAll\(\s*['"]([^'"]+)['"]\s*\)\.length$/);
|
|
627
|
+
if (qsaLenMatch) {
|
|
628
|
+
return { result: JSON.stringify(document.querySelectorAll(qsaLenMatch[1]).length) };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// Pattern: document.body.innerText / .innerHTML / .textContent
|
|
632
|
+
const bodyMatch = trimmed.match(/^document\.body\.(innerText|innerHTML|textContent)$/);
|
|
633
|
+
if (bodyMatch) {
|
|
634
|
+
const text = document.body[bodyMatch[1]];
|
|
635
|
+
return { result: JSON.stringify(text.length > 50000 ? text.slice(0, 50000) + "..." : text) };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// Pattern: window.innerWidth, window.innerHeight, window.scrollX, etc.
|
|
639
|
+
const winMatch = trimmed.match(/^window\.(innerWidth|innerHeight|outerWidth|outerHeight|scrollX|scrollY|devicePixelRatio)$/);
|
|
640
|
+
if (winMatch) {
|
|
641
|
+
return { result: JSON.stringify(window[winMatch[1]]) };
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Pattern: string literals — 'hello' or "hello"
|
|
645
|
+
const strLitMatch = trimmed.match(/^(['"])(.*)\1$/s);
|
|
646
|
+
if (strLitMatch) {
|
|
647
|
+
return { result: JSON.stringify(strLitMatch[2]) };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Pattern: boolean, null, undefined literals
|
|
651
|
+
if (/^(true|false|null|undefined)$/.test(trimmed)) {
|
|
652
|
+
const val = { true: true, false: false, null: null, undefined: undefined }[trimmed];
|
|
653
|
+
return { result: JSON.stringify(val) };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// Pattern: pure arithmetic — digits, operators, parens, spaces, decimals
|
|
657
|
+
// Safe because no identifiers can appear; parsed without eval()
|
|
658
|
+
if (/^[\d\s+\-*/%().]+$/.test(trimmed) && /\d/.test(trimmed)) {
|
|
659
|
+
const arithResult = safeArithmetic(trimmed);
|
|
660
|
+
if (arithResult !== null) return { result: JSON.stringify(arithResult) };
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Neither MAIN world nor the fallback patterns matched — surface both.
|
|
664
|
+
return {
|
|
665
|
+
error:
|
|
666
|
+
"javascript_exec: MAIN world unavailable and expression does not match " +
|
|
667
|
+
"the fallback DOM-property evaluator. MAIN world error: " + mainErrMsg + ". " +
|
|
668
|
+
"Fallback supports document.title, getElementById('x').textContent, " +
|
|
669
|
+
"querySelector('sel').value, window.innerWidth, 1+1, and similar reads. " +
|
|
670
|
+
"For complex queries on strict-CSP pages, use read_page, find, or form_input.",
|
|
671
|
+
};
|
|
672
|
+
} catch (err) {
|
|
673
|
+
return { error: err.message || String(err) };
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* Safe arithmetic evaluator — recursive descent parser for basic math.
|
|
679
|
+
* Handles +, -, *, /, %, parentheses, unary minus, decimals.
|
|
680
|
+
* No eval/Function needed — CSP-safe for MV3 extensions.
|
|
681
|
+
* Returns null if expression is malformed.
|
|
682
|
+
*/
|
|
683
|
+
function safeArithmetic(expr) {
|
|
684
|
+
let pos = 0;
|
|
685
|
+
const ch = () => expr[pos] || "";
|
|
686
|
+
const skip = () => { while (pos < expr.length && expr[pos] === " ") pos++; };
|
|
687
|
+
|
|
688
|
+
function parseExpr() {
|
|
689
|
+
let left = parseTerm();
|
|
690
|
+
skip();
|
|
691
|
+
while (ch() === "+" || ch() === "-") {
|
|
692
|
+
const op = ch(); pos++; skip();
|
|
693
|
+
const right = parseTerm();
|
|
694
|
+
left = op === "+" ? left + right : left - right;
|
|
695
|
+
skip(); // skip spaces before next operator
|
|
696
|
+
}
|
|
697
|
+
return left;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function parseTerm() {
|
|
701
|
+
let left = parseFactor();
|
|
702
|
+
skip();
|
|
703
|
+
while (ch() === "*" || ch() === "/" || ch() === "%") {
|
|
704
|
+
const op = ch(); pos++; skip();
|
|
705
|
+
const right = parseFactor();
|
|
706
|
+
if (op === "*") left *= right;
|
|
707
|
+
else if (op === "/") left /= right;
|
|
708
|
+
else left %= right;
|
|
709
|
+
skip(); // skip spaces before next operator
|
|
710
|
+
}
|
|
711
|
+
return left;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function parseFactor() {
|
|
715
|
+
skip();
|
|
716
|
+
if (ch() === "(") {
|
|
717
|
+
pos++;
|
|
718
|
+
const val = parseExpr();
|
|
719
|
+
skip();
|
|
720
|
+
if (ch() === ")") pos++;
|
|
721
|
+
return val;
|
|
722
|
+
}
|
|
723
|
+
if (ch() === "-") {
|
|
724
|
+
pos++;
|
|
725
|
+
return -parseFactor();
|
|
726
|
+
}
|
|
727
|
+
let numStr = "";
|
|
728
|
+
while (pos < expr.length && (/\d/.test(ch()) || ch() === ".")) {
|
|
729
|
+
numStr += ch(); pos++;
|
|
730
|
+
}
|
|
731
|
+
if (!numStr) return NaN;
|
|
732
|
+
return parseFloat(numStr);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
try {
|
|
736
|
+
const result = parseExpr();
|
|
737
|
+
skip();
|
|
738
|
+
if (pos < expr.length) return null; // unparsed trailing input
|
|
739
|
+
if (!isFinite(result)) return null;
|
|
740
|
+
return result;
|
|
741
|
+
} catch {
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// --- click, type, key, scroll, hover -----------------------------------------
|
|
747
|
+
|
|
748
|
+
function simulateClick(params) {
|
|
749
|
+
const { x, y, button, clickCount, ref, modifiers } = params;
|
|
750
|
+
|
|
751
|
+
// Resolve target: ref-based click takes priority over coordinate-based
|
|
752
|
+
let el;
|
|
753
|
+
if (ref) {
|
|
754
|
+
el = resolveRef(ref);
|
|
755
|
+
if (!el) return { error: `Element ${ref} not found` };
|
|
756
|
+
} else {
|
|
757
|
+
el = document.elementFromPoint(x, y);
|
|
758
|
+
if (!el) return { error: `No element at (${x}, ${y})` };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const eventType = button === "right" ? "contextmenu" : "click";
|
|
762
|
+
const mouseButton = button === "right" ? 2 : 0;
|
|
763
|
+
const mods = modifiers || {};
|
|
764
|
+
|
|
765
|
+
// Use element center if clicking by ref
|
|
766
|
+
let cx = x, cy = y;
|
|
767
|
+
if (ref && el) {
|
|
768
|
+
const rect = el.getBoundingClientRect();
|
|
769
|
+
cx = rect.x + rect.width / 2;
|
|
770
|
+
cy = rect.y + rect.height / 2;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
for (let i = 0; i < (clickCount || 1); i++) {
|
|
774
|
+
el.dispatchEvent(new MouseEvent("mousedown", { clientX: cx, clientY: cy, button: mouseButton, bubbles: true, ...mods }));
|
|
775
|
+
el.dispatchEvent(new MouseEvent("mouseup", { clientX: cx, clientY: cy, button: mouseButton, bubbles: true, ...mods }));
|
|
776
|
+
el.dispatchEvent(new MouseEvent(eventType, { clientX: cx, clientY: cy, button: mouseButton, bubbles: true, ...mods }));
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const tag = el.tagName.toLowerCase();
|
|
780
|
+
return { result: `Clicked at (${Math.round(cx)}, ${Math.round(cy)}) on <${tag}>${ref ? ` (${ref})` : ""}` };
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function typeText(params) {
|
|
784
|
+
const { text, modifiers } = params;
|
|
785
|
+
const el = document.activeElement || document.body;
|
|
786
|
+
const mods = modifiers || {};
|
|
787
|
+
|
|
788
|
+
for (const char of text) {
|
|
789
|
+
el.dispatchEvent(new KeyboardEvent("keydown", { key: char, bubbles: true, ...mods }));
|
|
790
|
+
el.dispatchEvent(new KeyboardEvent("keypress", { key: char, bubbles: true, ...mods }));
|
|
791
|
+
|
|
792
|
+
if (el.tagName === "INPUT" || el.tagName === "TEXTAREA") {
|
|
793
|
+
el.value += char;
|
|
794
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
el.dispatchEvent(new KeyboardEvent("keyup", { key: char, bubbles: true, ...mods }));
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
return { result: `Typed ${text.length} characters` };
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function keyPress(params) {
|
|
804
|
+
const { keys, modifiers } = params;
|
|
805
|
+
const el = document.activeElement || document.body;
|
|
806
|
+
const mods = modifiers || {};
|
|
807
|
+
|
|
808
|
+
for (const key of keys.split(" ")) {
|
|
809
|
+
el.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, ...mods }));
|
|
810
|
+
el.dispatchEvent(new KeyboardEvent("keyup", { key, bubbles: true, ...mods }));
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
return { result: `Pressed: ${keys}` };
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function scroll(params) {
|
|
817
|
+
const { x, y, direction, amount } = params;
|
|
818
|
+
|
|
819
|
+
// If direction is specified, use it (up/down/left/right with amount 1-10, ×100px)
|
|
820
|
+
if (direction) {
|
|
821
|
+
const px = (amount || 3) * 100;
|
|
822
|
+
const scrollMap = {
|
|
823
|
+
up: [0, -px],
|
|
824
|
+
down: [0, px],
|
|
825
|
+
left: [-px, 0],
|
|
826
|
+
right: [px, 0],
|
|
827
|
+
};
|
|
828
|
+
const [sx, sy] = scrollMap[direction] || [0, 0];
|
|
829
|
+
window.scrollBy(sx, sy);
|
|
830
|
+
return { result: `Scrolled ${direction} by ${px}px` };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// Legacy coordinate-based scroll
|
|
834
|
+
window.scrollBy(x, y);
|
|
835
|
+
return { result: `Scrolled by (${x}, ${y})` };
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function scrollTo(params) {
|
|
839
|
+
const { ref } = params;
|
|
840
|
+
const el = resolveRef(ref);
|
|
841
|
+
if (!el) return { error: `Element ${ref} not found` };
|
|
842
|
+
|
|
843
|
+
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
844
|
+
return { result: `Scrolled to ${ref}` };
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
function simulateHover(params) {
|
|
848
|
+
const { x, y, modifiers } = params;
|
|
849
|
+
const el = document.elementFromPoint(x, y);
|
|
850
|
+
if (!el) return { error: `No element at (${x}, ${y})` };
|
|
851
|
+
const mods = modifiers || {};
|
|
852
|
+
|
|
853
|
+
el.dispatchEvent(new MouseEvent("mouseover", { clientX: x, clientY: y, bubbles: true, ...mods }));
|
|
854
|
+
el.dispatchEvent(new MouseEvent("mouseenter", { clientX: x, clientY: y, bubbles: true, ...mods }));
|
|
855
|
+
|
|
856
|
+
return { result: `Hovering at (${x}, ${y})` };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// --- screenshot (fallback) ---------------------------------------------------
|
|
860
|
+
|
|
861
|
+
async function takeScreenshot(_params) {
|
|
862
|
+
// Without captureVisibleTab, we use a canvas-based approach
|
|
863
|
+
try {
|
|
864
|
+
// Try html2canvas if available
|
|
865
|
+
if (typeof html2canvas === "function") {
|
|
866
|
+
const canvas = await html2canvas(document.body, { scale: 0.5 });
|
|
867
|
+
return { result: canvas.toDataURL("image/png"), type: "image/png" };
|
|
868
|
+
}
|
|
869
|
+
} catch {}
|
|
870
|
+
|
|
871
|
+
// Fallback: return page HTML summary
|
|
872
|
+
return {
|
|
873
|
+
result: "Screenshot not available on Android. Page title: " + document.title +
|
|
874
|
+
", URL: " + location.href +
|
|
875
|
+
", Body text length: " + document.body.innerText.length,
|
|
876
|
+
note: "captureVisibleTab unavailable on mobile, html2canvas not loaded",
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// --- clear_console -----------------------------------------------------------
|
|
881
|
+
|
|
882
|
+
function clearConsole() {
|
|
883
|
+
const count = capturedConsole.length;
|
|
884
|
+
capturedConsole.length = 0;
|
|
885
|
+
return { result: `Console cleared (${count} entries removed)` };
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// --- get_storage / delete_storage_item ---------------------------------------
|
|
889
|
+
|
|
890
|
+
function getStorage() {
|
|
891
|
+
const result = { localStorage: [], sessionStorage: [] };
|
|
892
|
+
try {
|
|
893
|
+
for (const [key, value] of Object.entries(localStorage)) {
|
|
894
|
+
result.localStorage.push({
|
|
895
|
+
key,
|
|
896
|
+
value: value.length > 500 ? value.slice(0, 500) + "..." : value,
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
} catch (e) {
|
|
900
|
+
result.localStorage = [{ error: e.message || "Access denied" }];
|
|
901
|
+
}
|
|
902
|
+
try {
|
|
903
|
+
for (const [key, value] of Object.entries(sessionStorage)) {
|
|
904
|
+
result.sessionStorage.push({
|
|
905
|
+
key,
|
|
906
|
+
value: value.length > 500 ? value.slice(0, 500) + "..." : value,
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
} catch (e) {
|
|
910
|
+
result.sessionStorage = [{ error: e.message || "Access denied" }];
|
|
911
|
+
}
|
|
912
|
+
return { result };
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function deleteStorageItem(params) {
|
|
916
|
+
const { storageType, key } = params;
|
|
917
|
+
try {
|
|
918
|
+
if (storageType === "local") {
|
|
919
|
+
localStorage.removeItem(key);
|
|
920
|
+
return { result: `Removed '${key}' from localStorage` };
|
|
921
|
+
}
|
|
922
|
+
if (storageType === "session") {
|
|
923
|
+
sessionStorage.removeItem(key);
|
|
924
|
+
return { result: `Removed '${key}' from sessionStorage` };
|
|
925
|
+
}
|
|
926
|
+
return { error: `Unknown storageType: ${storageType}` };
|
|
927
|
+
} catch (e) {
|
|
928
|
+
return { error: e.message || "Storage access denied" };
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// --- read_console ------------------------------------------------------------
|
|
933
|
+
|
|
934
|
+
function readConsole(_params) {
|
|
935
|
+
return {
|
|
936
|
+
result: capturedConsole.slice(-50), // last 50 messages
|
|
937
|
+
count: capturedConsole.length,
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// --- get_page_text -----------------------------------------------------------
|
|
942
|
+
|
|
943
|
+
function getPageText(params) {
|
|
944
|
+
const { max_chars } = params;
|
|
945
|
+
const limit = max_chars || 100000;
|
|
946
|
+
let text = document.body.innerText || "";
|
|
947
|
+
if (text.length > limit) {
|
|
948
|
+
text = text.slice(0, limit) + "\n... [TRUNCATED at " + limit + " chars]";
|
|
949
|
+
}
|
|
950
|
+
return { result: text };
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// --- drag (left_click_drag) --------------------------------------------------
|
|
954
|
+
|
|
955
|
+
function simulateDrag(params) {
|
|
956
|
+
const { startX, startY, endX, endY, modifiers } = params;
|
|
957
|
+
const mods = modifiers || {};
|
|
958
|
+
|
|
959
|
+
const startEl = document.elementFromPoint(startX, startY);
|
|
960
|
+
if (!startEl) return { error: `No element at start (${startX}, ${startY})` };
|
|
961
|
+
|
|
962
|
+
// Mousedown at start position
|
|
963
|
+
startEl.dispatchEvent(new MouseEvent("mousedown", {
|
|
964
|
+
clientX: startX, clientY: startY, button: 0, bubbles: true, ...mods,
|
|
965
|
+
}));
|
|
966
|
+
|
|
967
|
+
// Interpolate mousemove steps for smoother drag
|
|
968
|
+
const steps = 10;
|
|
969
|
+
const dx = (endX - startX) / steps;
|
|
970
|
+
const dy = (endY - startY) / steps;
|
|
971
|
+
for (let i = 1; i <= steps; i++) {
|
|
972
|
+
const mx = startX + dx * i;
|
|
973
|
+
const my = startY + dy * i;
|
|
974
|
+
const moveEl = document.elementFromPoint(mx, my) || startEl;
|
|
975
|
+
moveEl.dispatchEvent(new MouseEvent("mousemove", {
|
|
976
|
+
clientX: mx, clientY: my, button: 0, bubbles: true, ...mods,
|
|
977
|
+
}));
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// Mouseup at end position
|
|
981
|
+
const endEl = document.elementFromPoint(endX, endY) || startEl;
|
|
982
|
+
endEl.dispatchEvent(new MouseEvent("mouseup", {
|
|
983
|
+
clientX: endX, clientY: endY, button: 0, bubbles: true, ...mods,
|
|
984
|
+
}));
|
|
985
|
+
|
|
986
|
+
return { result: `Dragged from (${startX}, ${startY}) to (${endX}, ${endY})` };
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// --- upload_image (file input via DataTransfer) ------------------------------
|
|
990
|
+
|
|
991
|
+
function uploadImage(params) {
|
|
992
|
+
const { ref, x, y, image_data } = params;
|
|
993
|
+
|
|
994
|
+
// Resolve target element
|
|
995
|
+
let el;
|
|
996
|
+
if (ref) {
|
|
997
|
+
el = resolveRef(ref);
|
|
998
|
+
if (!el) return { error: `Element ${ref} not found` };
|
|
999
|
+
} else if (x !== undefined && y !== undefined) {
|
|
1000
|
+
el = document.elementFromPoint(x, y);
|
|
1001
|
+
if (!el) return { error: `No element at (${x}, ${y})` };
|
|
1002
|
+
} else {
|
|
1003
|
+
return { error: "Must provide ref or coordinate for upload target" };
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
if (!image_data) return { error: "Missing image_data (base64)" };
|
|
1007
|
+
|
|
1008
|
+
try {
|
|
1009
|
+
// Decode base64 to binary
|
|
1010
|
+
const binaryStr = atob(image_data.replace(/^data:image\/\w+;base64,/, ""));
|
|
1011
|
+
const bytes = new Uint8Array(binaryStr.length);
|
|
1012
|
+
for (let i = 0; i < binaryStr.length; i++) {
|
|
1013
|
+
bytes[i] = binaryStr.charCodeAt(i);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// Create File from binary data
|
|
1017
|
+
const blob = new Blob([bytes], { type: "image/png" });
|
|
1018
|
+
const file = new File([blob], "upload.png", { type: "image/png" });
|
|
1019
|
+
|
|
1020
|
+
// If target is a file input, set via DataTransfer
|
|
1021
|
+
if (el.tagName === "INPUT" && el.type === "file") {
|
|
1022
|
+
const dt = new DataTransfer();
|
|
1023
|
+
dt.items.add(file);
|
|
1024
|
+
el.files = dt.files;
|
|
1025
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1026
|
+
return { result: `Set file input to upload.png (${bytes.length} bytes)` };
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// Otherwise, simulate a drop event
|
|
1030
|
+
const dt = new DataTransfer();
|
|
1031
|
+
dt.items.add(file);
|
|
1032
|
+
const rect = el.getBoundingClientRect();
|
|
1033
|
+
const dropX = rect.x + rect.width / 2;
|
|
1034
|
+
const dropY = rect.y + rect.height / 2;
|
|
1035
|
+
|
|
1036
|
+
el.dispatchEvent(new DragEvent("dragenter", { dataTransfer: dt, clientX: dropX, clientY: dropY, bubbles: true }));
|
|
1037
|
+
el.dispatchEvent(new DragEvent("dragover", { dataTransfer: dt, clientX: dropX, clientY: dropY, bubbles: true }));
|
|
1038
|
+
el.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, clientX: dropX, clientY: dropY, bubbles: true }));
|
|
1039
|
+
|
|
1040
|
+
return { result: `Dropped image on <${el.tagName.toLowerCase()}> (${bytes.length} bytes)` };
|
|
1041
|
+
} catch (err) {
|
|
1042
|
+
return { error: `Upload failed: ${err.message}` };
|
|
1043
|
+
}
|
|
1044
|
+
}
|