@pyrokine/mcp-chrome 2.4.4 → 3.0.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/README.md +495 -115
- package/README_zh.md +423 -128
- package/dist/anti-detection/injection.js +3 -3
- package/dist/cdp/client.d.ts +1 -1
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +18 -7
- package/dist/cdp/client.js.map +1 -1
- package/dist/cdp/launcher.d.ts +2 -3
- package/dist/cdp/launcher.d.ts.map +1 -1
- package/dist/cdp/launcher.js +84 -24
- package/dist/cdp/launcher.js.map +1 -1
- package/dist/core/auto-wait.d.ts +3 -3
- package/dist/core/auto-wait.d.ts.map +1 -1
- package/dist/core/auto-wait.js +45 -20
- package/dist/core/auto-wait.js.map +1 -1
- package/dist/core/browser-driver.d.ts +105 -15
- package/dist/core/browser-driver.d.ts.map +1 -1
- package/dist/core/browser-driver.js.map +1 -1
- package/dist/core/errors.d.ts +22 -4
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +90 -7
- package/dist/core/errors.js.map +1 -1
- package/dist/core/locator.d.ts +7 -0
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +54 -29
- package/dist/core/locator.js.map +1 -1
- package/dist/core/os-mouse.d.ts +15 -2
- package/dist/core/os-mouse.d.ts.map +1 -1
- package/dist/core/os-mouse.js +52 -8
- package/dist/core/os-mouse.js.map +1 -1
- package/dist/core/session.d.ts +39 -22
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +632 -153
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +2 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/unified-session.d.ts +105 -27
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +554 -138
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +5 -0
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +475 -54
- package/dist/core/utils.js.map +1 -1
- package/dist/extension/bridge.d.ts +49 -39
- package/dist/extension/bridge.d.ts.map +1 -1
- package/dist/extension/bridge.js +318 -131
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +3 -0
- package/dist/extension/http-server.d.ts.map +1 -1
- package/dist/extension/http-server.js +28 -2
- package/dist/extension/http-server.js.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/tools/browse.d.ts.map +1 -1
- package/dist/tools/browse.js +248 -172
- package/dist/tools/browse.js.map +1 -1
- package/dist/tools/challenge.d.ts +1 -1
- package/dist/tools/challenge.d.ts.map +1 -1
- package/dist/tools/challenge.js +86 -51
- package/dist/tools/challenge.js.map +1 -1
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +5 -3
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts +3 -3
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +13 -12
- package/dist/tools/diagnostics.js.map +1 -1
- package/dist/tools/evaluate.d.ts.map +1 -1
- package/dist/tools/evaluate.js +67 -26
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +137 -197
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +445 -197
- package/dist/tools/input.js.map +1 -1
- package/dist/tools/logs.d.ts.map +1 -1
- package/dist/tools/logs.js +5 -5
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/manage.d.ts.map +1 -1
- package/dist/tools/manage.js +395 -86
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/page-context.d.ts +17 -0
- package/dist/tools/page-context.d.ts.map +1 -0
- package/dist/tools/page-context.js +103 -0
- package/dist/tools/page-context.js.map +1 -0
- package/dist/tools/png.d.ts +5 -0
- package/dist/tools/png.d.ts.map +1 -1
- package/dist/tools/png.js +84 -19
- package/dist/tools/png.js.map +1 -1
- package/dist/tools/post-condition.d.ts.map +1 -1
- package/dist/tools/post-condition.js +24 -7
- package/dist/tools/post-condition.js.map +1 -1
- package/dist/tools/schema.d.ts +9 -0
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +15 -0
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/target-diagnostics.d.ts +9 -1
- package/dist/tools/target-diagnostics.d.ts.map +1 -1
- package/dist/tools/target-diagnostics.js +89 -33
- package/dist/tools/target-diagnostics.js.map +1 -1
- package/dist/tools/wait.d.ts.map +1 -1
- package/dist/tools/wait.js +38 -32
- package/dist/tools/wait.js.map +1 -1
- package/extension/dist/assets/content.ts-loader-DUWbDHRS.js +13 -0
- package/extension/dist/assets/content.ts-qe6IB5DK.js +13 -0
- package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-D7_LCUoV.js} +2477 -2201
- package/extension/dist/assets/page-scripts-D508WLkW.js +1378 -0
- package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-B-eVq48O.js} +54 -5
- package/extension/dist/manifest.json +4 -3
- package/extension/dist/service-worker-loader.js +1 -1
- package/extension/dist/src/popup/popup.html +11 -1
- package/package.json +16 -8
- package/scripts/start-chrome.ps1 +58 -0
- package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
|
@@ -0,0 +1,1378 @@
|
|
|
1
|
+
//#region src/background/page-scripts.ts
|
|
2
|
+
function installFrameProbeListener() {
|
|
3
|
+
const probeWindow = window;
|
|
4
|
+
if (probeWindow.__mcpFrameProbeListenerV2) return;
|
|
5
|
+
const onMessage = async (event) => {
|
|
6
|
+
const data = event.data;
|
|
7
|
+
if (event.source !== window.parent || data?.type !== "mcp-frame-probe-v2" || typeof data.token !== "string" || data.token.length > 100 || !Number.isInteger(data.index) || (data.index ?? -1) < 0) return;
|
|
8
|
+
const source = event.source;
|
|
9
|
+
try {
|
|
10
|
+
const runtime = typeof chrome === "undefined" ? void 0 : chrome.runtime;
|
|
11
|
+
if (typeof runtime?.sendMessage !== "function") throw new Error("Extension context invalidated: runtime messaging is unavailable");
|
|
12
|
+
if ((await runtime.sendMessage({
|
|
13
|
+
type: "MCP_FRAME_PROBE",
|
|
14
|
+
token: data.token,
|
|
15
|
+
index: data.index
|
|
16
|
+
}))?.accepted) source.postMessage({
|
|
17
|
+
type: "mcp-frame-probe-ack-v2",
|
|
18
|
+
token: data.token,
|
|
19
|
+
index: data.index
|
|
20
|
+
}, "*");
|
|
21
|
+
} catch (error) {
|
|
22
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
23
|
+
if (/Extension context invalidated/i.test(message)) {
|
|
24
|
+
if (probeWindow.__mcpFrameProbeListenerV2 !== onMessage) return;
|
|
25
|
+
window.removeEventListener("message", onMessage);
|
|
26
|
+
delete probeWindow.__mcpFrameProbeListenerV2;
|
|
27
|
+
}
|
|
28
|
+
console.warn("[MCP] iframe identity probe failed:", message);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
window.addEventListener("message", onMessage);
|
|
32
|
+
probeWindow.__mcpFrameProbeListenerV2 = onMessage;
|
|
33
|
+
}
|
|
34
|
+
function generateAccessibilityTree(filter, maxDepth, maxLength, refId, expectedUrl) {
|
|
35
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
36
|
+
const win = window;
|
|
37
|
+
win.__mcpElementMap = win.__mcpElementMap || {};
|
|
38
|
+
win.__mcpElementToRefId = win.__mcpElementToRefId || /* @__PURE__ */ new WeakMap();
|
|
39
|
+
win.__mcpRefCounter = win.__mcpRefCounter || 0;
|
|
40
|
+
const lines = [];
|
|
41
|
+
function getRole(element) {
|
|
42
|
+
const role = element.getAttribute("role");
|
|
43
|
+
if (role) return role;
|
|
44
|
+
const tag = element.tagName.toLowerCase();
|
|
45
|
+
const type = element.getAttribute("type");
|
|
46
|
+
return {
|
|
47
|
+
a: "link",
|
|
48
|
+
button: "button",
|
|
49
|
+
input: type === "submit" || type === "button" ? "button" : type === "checkbox" ? "checkbox" : type === "radio" ? "radio" : type === "file" ? "button" : "textbox",
|
|
50
|
+
select: "combobox",
|
|
51
|
+
textarea: "textbox",
|
|
52
|
+
h1: "heading",
|
|
53
|
+
h2: "heading",
|
|
54
|
+
h3: "heading",
|
|
55
|
+
h4: "heading",
|
|
56
|
+
h5: "heading",
|
|
57
|
+
h6: "heading",
|
|
58
|
+
img: "image",
|
|
59
|
+
nav: "navigation",
|
|
60
|
+
main: "main",
|
|
61
|
+
header: "banner",
|
|
62
|
+
footer: "contentinfo",
|
|
63
|
+
section: "region",
|
|
64
|
+
article: "article",
|
|
65
|
+
aside: "complementary",
|
|
66
|
+
form: "form",
|
|
67
|
+
table: "table",
|
|
68
|
+
ul: "list",
|
|
69
|
+
ol: "list",
|
|
70
|
+
li: "listitem",
|
|
71
|
+
label: "label"
|
|
72
|
+
}[tag] || "generic";
|
|
73
|
+
}
|
|
74
|
+
function getName(element) {
|
|
75
|
+
const tag = element.tagName.toLowerCase();
|
|
76
|
+
if (tag === "select") {
|
|
77
|
+
const select = element;
|
|
78
|
+
const selected = select.querySelector("option[selected]") || select.options[select.selectedIndex];
|
|
79
|
+
if (selected?.textContent) return selected.textContent.trim();
|
|
80
|
+
}
|
|
81
|
+
const ariaLabel = element.getAttribute("aria-label");
|
|
82
|
+
if (ariaLabel?.trim()) return ariaLabel.trim();
|
|
83
|
+
const placeholder = element.getAttribute("placeholder");
|
|
84
|
+
if (placeholder?.trim()) return placeholder.trim();
|
|
85
|
+
const title = element.getAttribute("title");
|
|
86
|
+
if (title?.trim()) return title.trim();
|
|
87
|
+
const alt = element.getAttribute("alt");
|
|
88
|
+
if (alt?.trim()) return alt.trim();
|
|
89
|
+
if (element.id) {
|
|
90
|
+
const label = document.querySelector(`label[for="${CSS.escape(element.id)}"]`);
|
|
91
|
+
if (label?.textContent?.trim()) return label.textContent.trim();
|
|
92
|
+
}
|
|
93
|
+
if (tag === "input") {
|
|
94
|
+
const input = element;
|
|
95
|
+
const inputType = input.type || "";
|
|
96
|
+
if (inputType !== "hidden" && inputType !== "password") {
|
|
97
|
+
const value = input.value;
|
|
98
|
+
if (value && (inputType === "submit" || value.length < 50)) return value.trim();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if ([
|
|
102
|
+
"button",
|
|
103
|
+
"a",
|
|
104
|
+
"summary"
|
|
105
|
+
].includes(tag)) {
|
|
106
|
+
let text = "";
|
|
107
|
+
for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) text += child.textContent;
|
|
108
|
+
if (text.trim()) return text.trim();
|
|
109
|
+
}
|
|
110
|
+
if (tag.match(/^h[1-6]$/)) {
|
|
111
|
+
const text = element.textContent;
|
|
112
|
+
if (text?.trim()) return text.trim().substring(0, 100);
|
|
113
|
+
}
|
|
114
|
+
let textContent = "";
|
|
115
|
+
for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) textContent += child.textContent;
|
|
116
|
+
if (textContent.trim().length >= 3) {
|
|
117
|
+
const trimmed = textContent.trim();
|
|
118
|
+
return trimmed.length > 100 ? trimmed.substring(0, 100) + "..." : trimmed;
|
|
119
|
+
}
|
|
120
|
+
return "";
|
|
121
|
+
}
|
|
122
|
+
function isVisible(element) {
|
|
123
|
+
const style = window.getComputedStyle(element);
|
|
124
|
+
const el = element;
|
|
125
|
+
return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0" && el.offsetWidth > 0 && el.offsetHeight > 0;
|
|
126
|
+
}
|
|
127
|
+
function isInteractive(element) {
|
|
128
|
+
const tag = element.tagName.toLowerCase();
|
|
129
|
+
return [
|
|
130
|
+
"a",
|
|
131
|
+
"button",
|
|
132
|
+
"input",
|
|
133
|
+
"select",
|
|
134
|
+
"textarea",
|
|
135
|
+
"details",
|
|
136
|
+
"summary"
|
|
137
|
+
].includes(tag) || element.getAttribute("onclick") !== null || element.getAttribute("tabindex") !== null || element.getAttribute("role") === "button" || element.getAttribute("role") === "link" || element.getAttribute("contenteditable") === "true";
|
|
138
|
+
}
|
|
139
|
+
function isLandmark(element) {
|
|
140
|
+
const tag = element.tagName.toLowerCase();
|
|
141
|
+
return [
|
|
142
|
+
"h1",
|
|
143
|
+
"h2",
|
|
144
|
+
"h3",
|
|
145
|
+
"h4",
|
|
146
|
+
"h5",
|
|
147
|
+
"h6",
|
|
148
|
+
"nav",
|
|
149
|
+
"main",
|
|
150
|
+
"header",
|
|
151
|
+
"footer",
|
|
152
|
+
"section",
|
|
153
|
+
"article",
|
|
154
|
+
"aside"
|
|
155
|
+
].includes(tag) || element.getAttribute("role") !== null;
|
|
156
|
+
}
|
|
157
|
+
function shouldInclude(element, checkRefId) {
|
|
158
|
+
const tag = element.tagName.toLowerCase();
|
|
159
|
+
if ([
|
|
160
|
+
"script",
|
|
161
|
+
"style",
|
|
162
|
+
"meta",
|
|
163
|
+
"link",
|
|
164
|
+
"title",
|
|
165
|
+
"noscript"
|
|
166
|
+
].includes(tag)) return false;
|
|
167
|
+
if (filter !== "all" && element.getAttribute("aria-hidden") === "true") return false;
|
|
168
|
+
if (filter !== "all" && !isVisible(element)) return false;
|
|
169
|
+
if (filter !== "all" && !checkRefId) {
|
|
170
|
+
const rect = element.getBoundingClientRect();
|
|
171
|
+
if (!(rect.top < window.innerHeight && rect.bottom > 0 && rect.left < window.innerWidth && rect.right > 0)) return false;
|
|
172
|
+
}
|
|
173
|
+
if (filter === "interactive") return isInteractive(element);
|
|
174
|
+
if (isInteractive(element)) return true;
|
|
175
|
+
if (isLandmark(element)) return true;
|
|
176
|
+
if (getName(element).length > 0) return true;
|
|
177
|
+
const role = getRole(element);
|
|
178
|
+
return role !== "generic" && role !== "image";
|
|
179
|
+
}
|
|
180
|
+
function getOrCreateRef(element) {
|
|
181
|
+
const existing = win.__mcpElementToRefId.get(element);
|
|
182
|
+
if (existing && win.__mcpElementMap[existing]?.deref() === element) return existing;
|
|
183
|
+
const newRefId = `ref_${++win.__mcpRefCounter}`;
|
|
184
|
+
win.__mcpElementMap[newRefId] = new WeakRef(element);
|
|
185
|
+
win.__mcpElementToRefId.set(element, newRefId);
|
|
186
|
+
return newRefId;
|
|
187
|
+
}
|
|
188
|
+
function cssSelector(element) {
|
|
189
|
+
if (element.id) return `#${CSS.escape(element.id)}`;
|
|
190
|
+
const parts = [];
|
|
191
|
+
let current = element;
|
|
192
|
+
while (current && current !== document.body && parts.length < 4) {
|
|
193
|
+
const tag = current.tagName.toLowerCase();
|
|
194
|
+
const parent = current.parentElement;
|
|
195
|
+
if (!parent) {
|
|
196
|
+
parts.unshift(tag);
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
const currentTag = current.tagName;
|
|
200
|
+
const siblings = Array.from(parent.children).filter((child) => child.tagName === currentTag);
|
|
201
|
+
const nth = siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(current) + 1})` : "";
|
|
202
|
+
parts.unshift(`${tag}${nth}`);
|
|
203
|
+
current = parent;
|
|
204
|
+
}
|
|
205
|
+
return parts.join(" > ");
|
|
206
|
+
}
|
|
207
|
+
function isDisabled(element) {
|
|
208
|
+
return Boolean(element.disabled) || element.getAttribute("aria-disabled") === "true";
|
|
209
|
+
}
|
|
210
|
+
function isCovered(element) {
|
|
211
|
+
const rect = element.getBoundingClientRect();
|
|
212
|
+
if (rect.width <= 0 || rect.height <= 0) return false;
|
|
213
|
+
const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
|
|
214
|
+
return Boolean(hit && hit !== element && !element.contains(hit) && !hit.contains(element));
|
|
215
|
+
}
|
|
216
|
+
const interactiveElements = [];
|
|
217
|
+
function rememberInteractive(element, elementRefId, role, name) {
|
|
218
|
+
if (!isInteractive(element) || interactiveElements.length >= 100) return;
|
|
219
|
+
const rect = element.getBoundingClientRect();
|
|
220
|
+
interactiveElements.push({
|
|
221
|
+
refId: elementRefId,
|
|
222
|
+
role,
|
|
223
|
+
name,
|
|
224
|
+
selector: cssSelector(element),
|
|
225
|
+
visible: isVisible(element),
|
|
226
|
+
disabled: isDisabled(element),
|
|
227
|
+
bounds: {
|
|
228
|
+
x: rect.x,
|
|
229
|
+
y: rect.y,
|
|
230
|
+
width: rect.width,
|
|
231
|
+
height: rect.height
|
|
232
|
+
},
|
|
233
|
+
covered: isCovered(element)
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
function traverse(element, level, checkRefId) {
|
|
237
|
+
if (level > maxDepth || !element || !element.tagName) return;
|
|
238
|
+
const include = shouldInclude(element, checkRefId) || checkRefId && level === 0;
|
|
239
|
+
if (include) {
|
|
240
|
+
const role = getRole(element);
|
|
241
|
+
const name = getName(element);
|
|
242
|
+
const elementRefId = getOrCreateRef(element);
|
|
243
|
+
let line = " ".repeat(level) + role;
|
|
244
|
+
if (name) line += ` "${name.replace(/\s+/g, " ").replace(/"/g, "\\\"")}"`;
|
|
245
|
+
line += ` [${elementRefId}]`;
|
|
246
|
+
const href = element.getAttribute("href");
|
|
247
|
+
if (href) line += ` href="${href}"`;
|
|
248
|
+
const type = element.getAttribute("type");
|
|
249
|
+
if (type) line += ` type="${type}"`;
|
|
250
|
+
lines.push(line);
|
|
251
|
+
rememberInteractive(element, elementRefId, role, name);
|
|
252
|
+
if (element.tagName.toLowerCase() === "select") {
|
|
253
|
+
const select = element;
|
|
254
|
+
for (const option of select.options) {
|
|
255
|
+
let optLine = " ".repeat(level + 1) + "option";
|
|
256
|
+
const optText = option.textContent?.trim() || "";
|
|
257
|
+
if (optText) optLine += ` "${optText.replace(/\s+/g, " ").substring(0, 100).replace(/"/g, "\\\"")}"`;
|
|
258
|
+
if (option.selected) optLine += " (selected)";
|
|
259
|
+
if (option.value && option.value !== optText) optLine += ` value="${option.value.replace(/"/g, "\\\"")}"`;
|
|
260
|
+
lines.push(optLine);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (element.children && level < maxDepth) for (const child of element.children) traverse(child, include ? level + 1 : level, checkRefId);
|
|
265
|
+
}
|
|
266
|
+
if (refId) {
|
|
267
|
+
const ref = win.__mcpElementMap[refId];
|
|
268
|
+
if (!ref) return {
|
|
269
|
+
error: `Element with ref_id '${refId}' not found`,
|
|
270
|
+
pageContent: "",
|
|
271
|
+
viewport: {
|
|
272
|
+
width: window.innerWidth,
|
|
273
|
+
height: window.innerHeight
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
const element = ref.deref();
|
|
277
|
+
if (!element) return {
|
|
278
|
+
error: `Element with ref_id '${refId}' no longer exists`,
|
|
279
|
+
pageContent: "",
|
|
280
|
+
viewport: {
|
|
281
|
+
width: window.innerWidth,
|
|
282
|
+
height: window.innerHeight
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
traverse(element, 0, true);
|
|
286
|
+
} else if (document.body) traverse(document.body, 0, false);
|
|
287
|
+
{
|
|
288
|
+
const w = window;
|
|
289
|
+
const counter = (w.__mcpSweepCounter ?? 0) + 1;
|
|
290
|
+
w.__mcpSweepCounter = counter;
|
|
291
|
+
if (counter % 10 === 0 || Object.keys(win.__mcpElementMap).length > 500) {
|
|
292
|
+
for (const id of Object.keys(win.__mcpElementMap)) if (!win.__mcpElementMap[id].deref()) delete win.__mcpElementMap[id];
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const content = lines.join("\n");
|
|
296
|
+
if (maxLength && content.length > maxLength) return {
|
|
297
|
+
error: `Output exceeds ${maxLength} character limit (${content.length} characters)`,
|
|
298
|
+
pageContent: "",
|
|
299
|
+
viewport: {
|
|
300
|
+
width: window.innerWidth,
|
|
301
|
+
height: window.innerHeight
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
pageContent: content,
|
|
306
|
+
viewport: {
|
|
307
|
+
width: window.innerWidth,
|
|
308
|
+
height: window.innerHeight
|
|
309
|
+
},
|
|
310
|
+
interactiveElements
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function performClick(refId) {
|
|
314
|
+
const ref = window.__mcpElementMap?.[refId];
|
|
315
|
+
if (!ref) return {
|
|
316
|
+
success: false,
|
|
317
|
+
error: `Element ${refId} not found`
|
|
318
|
+
};
|
|
319
|
+
const element = ref.deref();
|
|
320
|
+
if (!element) return {
|
|
321
|
+
success: false,
|
|
322
|
+
error: `Element ${refId} no longer exists`
|
|
323
|
+
};
|
|
324
|
+
element.scrollIntoView({
|
|
325
|
+
behavior: "smooth",
|
|
326
|
+
block: "center"
|
|
327
|
+
});
|
|
328
|
+
const el = element;
|
|
329
|
+
el.focus();
|
|
330
|
+
el.click();
|
|
331
|
+
return { success: true };
|
|
332
|
+
}
|
|
333
|
+
function performType(refId, text, clear) {
|
|
334
|
+
const ref = window.__mcpElementMap?.[refId];
|
|
335
|
+
if (!ref) return {
|
|
336
|
+
success: false,
|
|
337
|
+
error: `Element ${refId} not found`
|
|
338
|
+
};
|
|
339
|
+
const element = ref.deref();
|
|
340
|
+
if (!element) return {
|
|
341
|
+
success: false,
|
|
342
|
+
error: `Element ${refId} no longer exists`
|
|
343
|
+
};
|
|
344
|
+
const el = element;
|
|
345
|
+
el.focus();
|
|
346
|
+
if ("value" in el) {
|
|
347
|
+
el.value = clear ? text : el.value + text;
|
|
348
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
349
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
350
|
+
} else if (element.contentEditable === "true") {
|
|
351
|
+
if (clear) element.textContent = text;
|
|
352
|
+
else element.textContent = (element.textContent || "") + text;
|
|
353
|
+
element.dispatchEvent(new Event("input", { bubbles: true }));
|
|
354
|
+
}
|
|
355
|
+
return { success: true };
|
|
356
|
+
}
|
|
357
|
+
function performScroll(x, y, refId) {
|
|
358
|
+
if (refId) {
|
|
359
|
+
const ref = window.__mcpElementMap?.[refId];
|
|
360
|
+
if (!ref) return {
|
|
361
|
+
success: false,
|
|
362
|
+
error: `Element ${refId} not found`,
|
|
363
|
+
scrollX: 0,
|
|
364
|
+
scrollY: 0
|
|
365
|
+
};
|
|
366
|
+
const element = ref.deref();
|
|
367
|
+
if (!element) return {
|
|
368
|
+
success: false,
|
|
369
|
+
error: `Element ${refId} no longer exists`,
|
|
370
|
+
scrollX: 0,
|
|
371
|
+
scrollY: 0
|
|
372
|
+
};
|
|
373
|
+
element.scrollBy(x, y);
|
|
374
|
+
return {
|
|
375
|
+
success: true,
|
|
376
|
+
scrollX: element.scrollLeft,
|
|
377
|
+
scrollY: element.scrollTop
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
window.scrollBy(x, y);
|
|
381
|
+
return {
|
|
382
|
+
success: true,
|
|
383
|
+
scrollX: window.scrollX,
|
|
384
|
+
scrollY: window.scrollY
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
async function executeCode(code, timeout) {
|
|
388
|
+
function evaluateSerializationError(message, suggestion, context) {
|
|
389
|
+
return JSON.stringify({ error: {
|
|
390
|
+
code: "NON_SERIALIZABLE_EVALUATE_RESULT",
|
|
391
|
+
message,
|
|
392
|
+
suggestion,
|
|
393
|
+
context
|
|
394
|
+
} });
|
|
395
|
+
}
|
|
396
|
+
function serializeEvaluateResult(result) {
|
|
397
|
+
if (result instanceof Node) {
|
|
398
|
+
const element = result instanceof Element ? result : result.parentElement;
|
|
399
|
+
return {
|
|
400
|
+
success: false,
|
|
401
|
+
error: evaluateSerializationError(`返回值是 DOM 节点 ${result.nodeName},不能直接 JSON 序列化`, "请返回 textContent、outerHTML、getAttribute(...) 等简单字段,或改用 extract type=\"text\"/\"html\"", {
|
|
402
|
+
nodeType: result.nodeType,
|
|
403
|
+
nodeName: result.nodeName,
|
|
404
|
+
selector: element?.id ? `#${CSS.escape(element.id)}` : element?.tagName.toLowerCase()
|
|
405
|
+
})
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
if (result instanceof NodeList || result instanceof HTMLCollection) return {
|
|
409
|
+
success: false,
|
|
410
|
+
error: evaluateSerializationError(`返回值是 ${result.constructor.name},不能直接 JSON 序列化`, "请用 Array.from(value).map(...) 提取需要的字段,例如 textContent、href、outerHTML", {
|
|
411
|
+
className: result.constructor.name,
|
|
412
|
+
length: result.length
|
|
413
|
+
})
|
|
414
|
+
};
|
|
415
|
+
try {
|
|
416
|
+
return {
|
|
417
|
+
success: true,
|
|
418
|
+
result: JSON.stringify(result)
|
|
419
|
+
};
|
|
420
|
+
} catch (error) {
|
|
421
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
422
|
+
return {
|
|
423
|
+
success: false,
|
|
424
|
+
error: evaluateSerializationError(`evaluate 返回值无法 JSON 序列化: ${errorMsg}`, "请返回字符串、数字、布尔值、数组或普通对象,避免返回循环引用、BigInt、DOM 对象", { error: errorMsg })
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
const result = new Function(`return (${code})`)();
|
|
430
|
+
if (timeout === void 0) return serializeEvaluateResult(await result);
|
|
431
|
+
const timedOut = Symbol("evaluate-timeout");
|
|
432
|
+
let timeoutId;
|
|
433
|
+
const timeoutResult = new Promise((resolve) => {
|
|
434
|
+
timeoutId = setTimeout(() => resolve(timedOut), timeout);
|
|
435
|
+
});
|
|
436
|
+
try {
|
|
437
|
+
const settled = await Promise.race([Promise.resolve(result), timeoutResult]);
|
|
438
|
+
if (settled === timedOut) return {
|
|
439
|
+
success: false,
|
|
440
|
+
error: `Evaluation timeout after ${timeout}ms`
|
|
441
|
+
};
|
|
442
|
+
return serializeEvaluateResult(settled);
|
|
443
|
+
} finally {
|
|
444
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
445
|
+
}
|
|
446
|
+
} catch (error) {
|
|
447
|
+
const errorMsg = error instanceof Error ? error.message : "Unknown error";
|
|
448
|
+
if (errorMsg.includes("Content Security Policy") || errorMsg.includes("'unsafe-eval'")) return {
|
|
449
|
+
success: false,
|
|
450
|
+
error: `CSP 限制:此页面禁止动态代码执行,建议使用 extract 工具获取页面内容或使用 CDP 模式,原始错误: ${errorMsg}`
|
|
451
|
+
};
|
|
452
|
+
return {
|
|
453
|
+
success: false,
|
|
454
|
+
error: errorMsg
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function extractText(selector, expectedUrl, refId) {
|
|
459
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
460
|
+
if (refId) {
|
|
461
|
+
const element = window.__mcpElementMap?.[refId]?.deref();
|
|
462
|
+
return { text: element?.isConnected ? element instanceof HTMLElement ? element.innerText : element.textContent ?? "" : "" };
|
|
463
|
+
}
|
|
464
|
+
if (selector) {
|
|
465
|
+
let element;
|
|
466
|
+
try {
|
|
467
|
+
element = document.querySelector(selector);
|
|
468
|
+
} catch (e) {
|
|
469
|
+
const err = e;
|
|
470
|
+
if (err?.name === "SyntaxError") return {
|
|
471
|
+
text: "",
|
|
472
|
+
error: `Invalid CSS selector: "${selector}" (${err.message})`
|
|
473
|
+
};
|
|
474
|
+
throw e;
|
|
475
|
+
}
|
|
476
|
+
return { text: element instanceof HTMLElement ? element.innerText : element?.textContent ?? "" };
|
|
477
|
+
}
|
|
478
|
+
return { text: document.body.innerText };
|
|
479
|
+
}
|
|
480
|
+
function extractHtml(selector, outer, expectedUrl, refId) {
|
|
481
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
482
|
+
if (refId) {
|
|
483
|
+
const element = window.__mcpElementMap?.[refId]?.deref();
|
|
484
|
+
return { html: element?.isConnected ? outer ? element.outerHTML : element.innerHTML : "" };
|
|
485
|
+
}
|
|
486
|
+
if (selector) {
|
|
487
|
+
let element;
|
|
488
|
+
try {
|
|
489
|
+
element = document.querySelector(selector);
|
|
490
|
+
} catch (e) {
|
|
491
|
+
const err = e;
|
|
492
|
+
if (err?.name === "SyntaxError") return {
|
|
493
|
+
html: "",
|
|
494
|
+
error: `Invalid CSS selector: "${selector}" (${err.message})`
|
|
495
|
+
};
|
|
496
|
+
throw e;
|
|
497
|
+
}
|
|
498
|
+
if (!element) return { html: "" };
|
|
499
|
+
return { html: outer ? element.outerHTML : element.innerHTML };
|
|
500
|
+
}
|
|
501
|
+
return { html: document.documentElement.outerHTML };
|
|
502
|
+
}
|
|
503
|
+
function extractHtmlWithImages(selector, outer, expectedUrl, refId) {
|
|
504
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
505
|
+
let root;
|
|
506
|
+
if (refId) {
|
|
507
|
+
const element = window.__mcpElementMap?.[refId]?.deref();
|
|
508
|
+
root = element?.isConnected ? element : null;
|
|
509
|
+
} else if (selector) try {
|
|
510
|
+
root = document.querySelector(selector);
|
|
511
|
+
} catch (e) {
|
|
512
|
+
const err = e;
|
|
513
|
+
if (err?.name === "SyntaxError") throw new Error(`Invalid CSS selector: "${selector}" (${err.message})`, { cause: e });
|
|
514
|
+
throw e;
|
|
515
|
+
}
|
|
516
|
+
else root = document.documentElement;
|
|
517
|
+
if (!root) return {
|
|
518
|
+
html: "",
|
|
519
|
+
images: []
|
|
520
|
+
};
|
|
521
|
+
const html = selector || refId ? outer ? root.outerHTML : root.innerHTML : document.documentElement.outerHTML;
|
|
522
|
+
const imgList = [];
|
|
523
|
+
if (root.tagName === "IMG") imgList.push(root);
|
|
524
|
+
root.querySelectorAll("img").forEach((img) => imgList.push(img));
|
|
525
|
+
return {
|
|
526
|
+
html,
|
|
527
|
+
images: imgList.map((img, index) => ({
|
|
528
|
+
index,
|
|
529
|
+
src: img.src,
|
|
530
|
+
dataSrc: (() => {
|
|
531
|
+
const raw = img.dataset.src || img.dataset.lazySrc || img.dataset.original || "";
|
|
532
|
+
if (!raw) return "";
|
|
533
|
+
try {
|
|
534
|
+
return new URL(raw, location.href).href;
|
|
535
|
+
} catch {
|
|
536
|
+
return raw;
|
|
537
|
+
}
|
|
538
|
+
})(),
|
|
539
|
+
alt: img.alt,
|
|
540
|
+
width: img.width,
|
|
541
|
+
height: img.height,
|
|
542
|
+
naturalWidth: img.naturalWidth,
|
|
543
|
+
naturalHeight: img.naturalHeight
|
|
544
|
+
}))
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function extractMetadata(expectedUrl) {
|
|
548
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
549
|
+
const meta = (name) => document.querySelector(`meta[name="${name}"],meta[property="${name}"]`)?.content || void 0;
|
|
550
|
+
return {
|
|
551
|
+
url: location.href || document.baseURI || void 0,
|
|
552
|
+
title: document.title,
|
|
553
|
+
description: meta("description"),
|
|
554
|
+
canonical: document.querySelector("link[rel=\"canonical\"]")?.href || void 0,
|
|
555
|
+
charset: document.characterSet,
|
|
556
|
+
viewport: meta("viewport"),
|
|
557
|
+
og: Object.fromEntries(Array.from(document.querySelectorAll("meta[property^=\"og:\"]")).map((m) => [m.getAttribute("property"), m.content ?? ""])),
|
|
558
|
+
twitter: Object.fromEntries(Array.from(document.querySelectorAll("meta[name^=\"twitter:\"]")).map((m) => [m.getAttribute("name"), m.content ?? ""])),
|
|
559
|
+
jsonLd: Array.from(document.querySelectorAll("script[type=\"application/ld+json\"]")).map((s) => {
|
|
560
|
+
try {
|
|
561
|
+
return JSON.parse(s.textContent ?? "");
|
|
562
|
+
} catch {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
}).filter(Boolean),
|
|
566
|
+
alternates: Array.from(document.querySelectorAll("link[rel=\"alternate\"]")).map((l) => ({
|
|
567
|
+
href: l.href,
|
|
568
|
+
type: l.getAttribute("type") || void 0,
|
|
569
|
+
hreflang: l.getAttribute("hreflang") || void 0
|
|
570
|
+
})),
|
|
571
|
+
feeds: Array.from(document.querySelectorAll("link[type=\"application/rss+xml\"],link[type=\"application/atom+xml\"]")).map((l) => ({
|
|
572
|
+
href: l.href,
|
|
573
|
+
type: l.getAttribute("type"),
|
|
574
|
+
title: l.getAttribute("title") || void 0
|
|
575
|
+
}))
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
function extractAttribute(selector, refId, attribute, expectedUrl) {
|
|
579
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
580
|
+
let element = null;
|
|
581
|
+
if (refId) element = (window.__mcpElementMap?.[refId])?.deref() ?? null;
|
|
582
|
+
else if (selector) try {
|
|
583
|
+
element = document.querySelector(selector);
|
|
584
|
+
} catch (e) {
|
|
585
|
+
const err = e;
|
|
586
|
+
if (err?.name === "SyntaxError") throw new Error(`Invalid CSS selector: "${selector}" (${err.message})`, { cause: e });
|
|
587
|
+
throw e;
|
|
588
|
+
}
|
|
589
|
+
if (!element) return { value: null };
|
|
590
|
+
if ([
|
|
591
|
+
"value",
|
|
592
|
+
"checked",
|
|
593
|
+
"selected",
|
|
594
|
+
"disabled",
|
|
595
|
+
"readOnly",
|
|
596
|
+
"indeterminate"
|
|
597
|
+
].includes(attribute)) {
|
|
598
|
+
const propValue = element[attribute];
|
|
599
|
+
if (typeof propValue === "boolean") return { value: propValue ? "true" : "false" };
|
|
600
|
+
return { value: propValue != null ? String(propValue) : null };
|
|
601
|
+
}
|
|
602
|
+
return { value: element.getAttribute(attribute) };
|
|
603
|
+
}
|
|
604
|
+
function findElements(selector, text, xpath, expectedUrl, point, matchIndex) {
|
|
605
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
606
|
+
const win = window;
|
|
607
|
+
win.__mcpElementMap = win.__mcpElementMap || {};
|
|
608
|
+
win.__mcpElementToRefId = win.__mcpElementToRefId || /* @__PURE__ */ new WeakMap();
|
|
609
|
+
win.__mcpRefCounter = win.__mcpRefCounter || 0;
|
|
610
|
+
const results = [];
|
|
611
|
+
let elements;
|
|
612
|
+
if (point) {
|
|
613
|
+
const element = document.elementFromPoint(point.x, point.y);
|
|
614
|
+
elements = element ? [element] : [];
|
|
615
|
+
} else if (xpath) {
|
|
616
|
+
elements = [];
|
|
617
|
+
const xpathResult = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
|
|
618
|
+
for (let i = 0; i < xpathResult.snapshotLength; i++) {
|
|
619
|
+
const node = xpathResult.snapshotItem(i);
|
|
620
|
+
if (node instanceof Element) elements.push(node);
|
|
621
|
+
}
|
|
622
|
+
} else if (selector) try {
|
|
623
|
+
elements = Array.from(document.querySelectorAll(selector));
|
|
624
|
+
} catch (e) {
|
|
625
|
+
const err = e;
|
|
626
|
+
if (err?.name === "SyntaxError") return { error: `Invalid CSS selector: "${selector}" (${err.message})` };
|
|
627
|
+
throw e;
|
|
628
|
+
}
|
|
629
|
+
else if (text) {
|
|
630
|
+
elements = [];
|
|
631
|
+
const seen = /* @__PURE__ */ new Set();
|
|
632
|
+
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, { acceptNode: (node) => node.data?.includes(text) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT });
|
|
633
|
+
let n = walker.nextNode();
|
|
634
|
+
let textMatchIndex = 0;
|
|
635
|
+
while (n && (matchIndex !== void 0 || elements.length < 200)) {
|
|
636
|
+
const parent = n.parentElement;
|
|
637
|
+
if (parent && !seen.has(parent)) {
|
|
638
|
+
seen.add(parent);
|
|
639
|
+
if (matchIndex === void 0 || textMatchIndex++ === matchIndex) {
|
|
640
|
+
elements.push(parent);
|
|
641
|
+
if (matchIndex !== void 0) break;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
n = walker.nextNode();
|
|
645
|
+
}
|
|
646
|
+
} else return { error: "find requires at least one of: selector, xpath, text" };
|
|
647
|
+
let matched = 0;
|
|
648
|
+
for (const element of elements) {
|
|
649
|
+
if (text) {
|
|
650
|
+
if (!(element.textContent || "").includes(text)) continue;
|
|
651
|
+
}
|
|
652
|
+
if (matchIndex !== void 0 && (selector || xpath || point) && matched++ !== matchIndex) continue;
|
|
653
|
+
let refId = win.__mcpElementToRefId.get(element) ?? null;
|
|
654
|
+
if (refId && win.__mcpElementMap[refId]?.deref() !== element) refId = null;
|
|
655
|
+
if (!refId) {
|
|
656
|
+
refId = `ref_${++win.__mcpRefCounter}`;
|
|
657
|
+
win.__mcpElementMap[refId] = new WeakRef(element);
|
|
658
|
+
win.__mcpElementToRefId.set(element, refId);
|
|
659
|
+
}
|
|
660
|
+
const rect = element.getBoundingClientRect();
|
|
661
|
+
results.push({
|
|
662
|
+
refId,
|
|
663
|
+
tag: element.tagName.toLowerCase(),
|
|
664
|
+
text: (element.textContent || "").trim().substring(0, 100),
|
|
665
|
+
rect: {
|
|
666
|
+
x: rect.x,
|
|
667
|
+
y: rect.y,
|
|
668
|
+
width: rect.width,
|
|
669
|
+
height: rect.height
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
if (matchIndex !== void 0 || results.length >= 50) break;
|
|
673
|
+
}
|
|
674
|
+
{
|
|
675
|
+
const w = window;
|
|
676
|
+
const counter = (w.__mcpSweepCounter ?? 0) + 1;
|
|
677
|
+
w.__mcpSweepCounter = counter;
|
|
678
|
+
if (counter % 10 === 0 || Object.keys(win.__mcpElementMap).length > 500) {
|
|
679
|
+
for (const id of Object.keys(win.__mcpElementMap)) if (!win.__mcpElementMap[id].deref()) delete win.__mcpElementMap[id];
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return results;
|
|
683
|
+
}
|
|
684
|
+
function simulateMouseClick(x, y, button, clickCount = 1, refId) {
|
|
685
|
+
let element = null;
|
|
686
|
+
if (refId) {
|
|
687
|
+
const resolved = (window.__mcpElementMap?.[refId])?.deref();
|
|
688
|
+
if (resolved && resolved.isConnected) {
|
|
689
|
+
element = resolved;
|
|
690
|
+
const r = resolved.getBoundingClientRect();
|
|
691
|
+
x = r.x + r.width / 2;
|
|
692
|
+
y = r.y + r.height / 2;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (!element) element = document.elementFromPoint(x, y);
|
|
696
|
+
if (!element) return { success: false };
|
|
697
|
+
const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
|
|
698
|
+
const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
|
|
699
|
+
const baseOptions = {
|
|
700
|
+
bubbles: true,
|
|
701
|
+
cancelable: true,
|
|
702
|
+
view: window,
|
|
703
|
+
clientX: x,
|
|
704
|
+
clientY: y,
|
|
705
|
+
screenX: x + window.screenX,
|
|
706
|
+
screenY: y + window.screenY,
|
|
707
|
+
button: buttonCode
|
|
708
|
+
};
|
|
709
|
+
const pressed = {
|
|
710
|
+
...baseOptions,
|
|
711
|
+
buttons: buttonsMask
|
|
712
|
+
};
|
|
713
|
+
const released = {
|
|
714
|
+
...baseOptions,
|
|
715
|
+
buttons: 0
|
|
716
|
+
};
|
|
717
|
+
element.dispatchEvent(new MouseEvent("mouseover", released));
|
|
718
|
+
element.dispatchEvent(new MouseEvent("mouseenter", {
|
|
719
|
+
...released,
|
|
720
|
+
bubbles: false
|
|
721
|
+
}));
|
|
722
|
+
element.dispatchEvent(new MouseEvent("mousemove", released));
|
|
723
|
+
const clickType = button === "right" ? "contextmenu" : button === "middle" ? "auxclick" : "click";
|
|
724
|
+
for (let detail = 1; detail <= clickCount; ++detail) {
|
|
725
|
+
element.dispatchEvent(new MouseEvent("mousedown", {
|
|
726
|
+
...pressed,
|
|
727
|
+
detail
|
|
728
|
+
}));
|
|
729
|
+
if (detail === 1 && "focus" in element && typeof element.focus === "function") element.focus();
|
|
730
|
+
element.dispatchEvent(new MouseEvent("mouseup", {
|
|
731
|
+
...released,
|
|
732
|
+
detail
|
|
733
|
+
}));
|
|
734
|
+
element.dispatchEvent(new MouseEvent(clickType, {
|
|
735
|
+
...released,
|
|
736
|
+
detail
|
|
737
|
+
}));
|
|
738
|
+
if (button === "left" && detail === 2) element.dispatchEvent(new MouseEvent("dblclick", {
|
|
739
|
+
...released,
|
|
740
|
+
detail
|
|
741
|
+
}));
|
|
742
|
+
}
|
|
743
|
+
return { success: true };
|
|
744
|
+
}
|
|
745
|
+
async function simulateKeyboardType(text, delay, deadline) {
|
|
746
|
+
const expired = () => deadline !== void 0 && Date.now() >= deadline;
|
|
747
|
+
const activeElement = document.activeElement;
|
|
748
|
+
if (!activeElement) return {
|
|
749
|
+
success: false,
|
|
750
|
+
error: "No active element"
|
|
751
|
+
};
|
|
752
|
+
if (!(activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.isContentEditable)) return {
|
|
753
|
+
success: false,
|
|
754
|
+
error: `Active element does not accept keyboard input: ${activeElement.tagName}`
|
|
755
|
+
};
|
|
756
|
+
const proto = Object.getPrototypeOf(activeElement);
|
|
757
|
+
const valueSetter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
|
|
758
|
+
const setNativeValue = (val) => {
|
|
759
|
+
if (valueSetter?.set) valueSetter.set.call(activeElement, val);
|
|
760
|
+
else if ("value" in activeElement) activeElement.value = val;
|
|
761
|
+
};
|
|
762
|
+
let firstCharacter = true;
|
|
763
|
+
for (const char of text.replace(/\r\n?/g, "\n")) {
|
|
764
|
+
if (expired()) return {
|
|
765
|
+
success: false,
|
|
766
|
+
error: "input timeout during typing"
|
|
767
|
+
};
|
|
768
|
+
if (delay > 0 && !firstCharacter) {
|
|
769
|
+
const remaining = deadline === void 0 ? delay : Math.max(0, deadline - Date.now());
|
|
770
|
+
await new Promise((r) => setTimeout(r, Math.min(delay, remaining)));
|
|
771
|
+
}
|
|
772
|
+
if (expired()) return {
|
|
773
|
+
success: false,
|
|
774
|
+
error: "input timeout during typing"
|
|
775
|
+
};
|
|
776
|
+
const keyEventOptions = {
|
|
777
|
+
bubbles: true,
|
|
778
|
+
cancelable: true,
|
|
779
|
+
key: char,
|
|
780
|
+
code: char >= "a" && char <= "z" ? `Key${char.toUpperCase()}` : char >= "A" && char <= "Z" ? `Key${char}` : char >= "0" && char <= "9" ? `Digit${char}` : "Key",
|
|
781
|
+
charCode: char.charCodeAt(0),
|
|
782
|
+
keyCode: char.charCodeAt(0),
|
|
783
|
+
which: char.charCodeAt(0),
|
|
784
|
+
view: window
|
|
785
|
+
};
|
|
786
|
+
activeElement.dispatchEvent(new KeyboardEvent("keydown", keyEventOptions));
|
|
787
|
+
activeElement.dispatchEvent(new KeyboardEvent("keypress", keyEventOptions));
|
|
788
|
+
if ("value" in activeElement) setNativeValue((activeElement.value ?? "") + char);
|
|
789
|
+
else if (activeElement.isContentEditable) activeElement.textContent = (activeElement.textContent || "") + char;
|
|
790
|
+
activeElement.dispatchEvent(new InputEvent("input", {
|
|
791
|
+
bubbles: true,
|
|
792
|
+
cancelable: true,
|
|
793
|
+
inputType: "insertText",
|
|
794
|
+
data: char
|
|
795
|
+
}));
|
|
796
|
+
activeElement.dispatchEvent(new KeyboardEvent("keyup", keyEventOptions));
|
|
797
|
+
firstCharacter = false;
|
|
798
|
+
}
|
|
799
|
+
if (expired()) return {
|
|
800
|
+
success: false,
|
|
801
|
+
error: "input timeout during typing"
|
|
802
|
+
};
|
|
803
|
+
activeElement.dispatchEvent(new Event("change", { bubbles: true }));
|
|
804
|
+
return { success: true };
|
|
805
|
+
}
|
|
806
|
+
function simulateKeyEvent(key, type, modifiers, deadline) {
|
|
807
|
+
if (deadline !== void 0 && Date.now() >= deadline) throw new Error("input timeout before event dispatch");
|
|
808
|
+
const activeElement = document.activeElement || document.body;
|
|
809
|
+
const keyEventOptions = {
|
|
810
|
+
bubbles: true,
|
|
811
|
+
cancelable: true,
|
|
812
|
+
key,
|
|
813
|
+
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
|
814
|
+
view: window,
|
|
815
|
+
ctrlKey: modifiers.includes("ctrl"),
|
|
816
|
+
shiftKey: modifiers.includes("shift"),
|
|
817
|
+
altKey: modifiers.includes("alt"),
|
|
818
|
+
metaKey: modifiers.includes("meta")
|
|
819
|
+
};
|
|
820
|
+
if (type === "down" || type === "press") activeElement.dispatchEvent(new KeyboardEvent("keydown", keyEventOptions));
|
|
821
|
+
if (type === "press") activeElement.dispatchEvent(new KeyboardEvent("keypress", keyEventOptions));
|
|
822
|
+
if (type === "up" || type === "press") activeElement.dispatchEvent(new KeyboardEvent("keyup", keyEventOptions));
|
|
823
|
+
return { success: true };
|
|
824
|
+
}
|
|
825
|
+
function simulateMouseEvent(type, x, y, button, deadline) {
|
|
826
|
+
if (deadline !== void 0 && Date.now() >= deadline) throw new Error("input timeout before mouse event dispatch");
|
|
827
|
+
const element = document.elementFromPoint(x, y) || document.body;
|
|
828
|
+
const buttonCode = button === "right" ? 2 : button === "middle" ? 1 : 0;
|
|
829
|
+
const buttonsMask = button === "right" ? 2 : button === "middle" ? 4 : 1;
|
|
830
|
+
const eventOptions = {
|
|
831
|
+
bubbles: true,
|
|
832
|
+
cancelable: true,
|
|
833
|
+
view: window,
|
|
834
|
+
clientX: x,
|
|
835
|
+
clientY: y,
|
|
836
|
+
screenX: x + window.screenX,
|
|
837
|
+
screenY: y + window.screenY,
|
|
838
|
+
button: buttonCode,
|
|
839
|
+
buttons: type === "mousedown" ? buttonsMask : 0
|
|
840
|
+
};
|
|
841
|
+
element.dispatchEvent(new MouseEvent(type, eventOptions));
|
|
842
|
+
if (type === "mousedown" && "focus" in element && typeof element.focus === "function") element.focus();
|
|
843
|
+
if (type === "mouseup") {
|
|
844
|
+
const clickType = button === "right" ? "contextmenu" : button === "middle" ? "auxclick" : "click";
|
|
845
|
+
element.dispatchEvent(new MouseEvent(clickType, eventOptions));
|
|
846
|
+
}
|
|
847
|
+
return { success: true };
|
|
848
|
+
}
|
|
849
|
+
function injectStealthScripts() {
|
|
850
|
+
Object.defineProperty(navigator, "webdriver", {
|
|
851
|
+
get: () => void 0,
|
|
852
|
+
configurable: true
|
|
853
|
+
});
|
|
854
|
+
Object.defineProperty(navigator, "plugins", {
|
|
855
|
+
get: () => {
|
|
856
|
+
const plugins = [
|
|
857
|
+
{
|
|
858
|
+
name: "Chrome PDF Plugin",
|
|
859
|
+
filename: "internal-pdf-viewer"
|
|
860
|
+
},
|
|
861
|
+
{
|
|
862
|
+
name: "Chrome PDF Viewer",
|
|
863
|
+
filename: "mhjfbmdgcfjbbpaeojofohoefgiehjai"
|
|
864
|
+
},
|
|
865
|
+
{
|
|
866
|
+
name: "Native Client",
|
|
867
|
+
filename: "internal-nacl-plugin"
|
|
868
|
+
}
|
|
869
|
+
];
|
|
870
|
+
const pluginArray = Object.create(globalThis.PluginArray.prototype);
|
|
871
|
+
plugins.forEach((p, i) => {
|
|
872
|
+
const plugin = Object.create(globalThis.Plugin.prototype);
|
|
873
|
+
Object.defineProperties(plugin, {
|
|
874
|
+
name: { value: p.name },
|
|
875
|
+
filename: { value: p.filename },
|
|
876
|
+
description: { value: "" },
|
|
877
|
+
length: { value: 0 }
|
|
878
|
+
});
|
|
879
|
+
pluginArray[i] = plugin;
|
|
880
|
+
});
|
|
881
|
+
Object.defineProperty(pluginArray, "length", { value: plugins.length });
|
|
882
|
+
return pluginArray;
|
|
883
|
+
},
|
|
884
|
+
configurable: true
|
|
885
|
+
});
|
|
886
|
+
Object.defineProperty(navigator, "languages", {
|
|
887
|
+
get: () => [
|
|
888
|
+
"zh-CN",
|
|
889
|
+
"zh",
|
|
890
|
+
"en-US",
|
|
891
|
+
"en"
|
|
892
|
+
],
|
|
893
|
+
configurable: true
|
|
894
|
+
});
|
|
895
|
+
const originalChrome = window.chrome;
|
|
896
|
+
const chromeDescriptor = Object.getOwnPropertyDescriptor(window, "chrome");
|
|
897
|
+
if (originalChrome && chromeDescriptor?.configurable) Object.defineProperty(window, "chrome", {
|
|
898
|
+
get: () => {
|
|
899
|
+
const chrome = { ...originalChrome };
|
|
900
|
+
delete chrome.runtime;
|
|
901
|
+
return chrome;
|
|
902
|
+
},
|
|
903
|
+
configurable: true
|
|
904
|
+
});
|
|
905
|
+
window.Error = new Proxy(Error, { construct(target, args) {
|
|
906
|
+
const error = new target(...args);
|
|
907
|
+
const originalStack = error.stack;
|
|
908
|
+
if (originalStack) error.stack = originalStack.split("\n").filter((line) => !line.includes("chrome-extension://")).join("\n");
|
|
909
|
+
return error;
|
|
910
|
+
} });
|
|
911
|
+
if (navigator.permissions) {
|
|
912
|
+
const originalQuery = navigator.permissions.query.bind(navigator.permissions);
|
|
913
|
+
navigator.permissions.query = async (descriptor) => {
|
|
914
|
+
if (descriptor.name === "notifications") return {
|
|
915
|
+
state: "prompt",
|
|
916
|
+
onchange: null
|
|
917
|
+
};
|
|
918
|
+
return originalQuery(descriptor);
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
const originalGetParameter = WebGLRenderingContext.prototype.getParameter;
|
|
922
|
+
WebGLRenderingContext.prototype.getParameter = function(parameter) {
|
|
923
|
+
if (parameter === 37445) return "Google Inc. (NVIDIA)";
|
|
924
|
+
if (parameter === 37446) return "ANGLE (NVIDIA, NVIDIA GeForce GTX 1080 Direct3D11 vs_5_0 ps_5_0, D3D11)";
|
|
925
|
+
return originalGetParameter.call(this, parameter);
|
|
926
|
+
};
|
|
927
|
+
console.log("[MCP Stealth] Anti-detection scripts injected");
|
|
928
|
+
}
|
|
929
|
+
function installActionabilityHelpers() {
|
|
930
|
+
const win = window;
|
|
931
|
+
function plainRect(r) {
|
|
932
|
+
return {
|
|
933
|
+
x: r.x,
|
|
934
|
+
y: r.y,
|
|
935
|
+
width: r.width,
|
|
936
|
+
height: r.height
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
function selectorFor(el) {
|
|
940
|
+
if (el.id) return `#${CSS.escape(el.id)}`;
|
|
941
|
+
const tag = el.tagName.toLowerCase();
|
|
942
|
+
const parent = el.parentElement;
|
|
943
|
+
if (!parent) return tag;
|
|
944
|
+
const siblings = Array.from(parent.children).filter((child) => child.tagName === el.tagName);
|
|
945
|
+
return `${tag}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(el) + 1})` : ""}`;
|
|
946
|
+
}
|
|
947
|
+
function textFor(el) {
|
|
948
|
+
return (el.textContent || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").trim().slice(0, 80);
|
|
949
|
+
}
|
|
950
|
+
function describeElement(el) {
|
|
951
|
+
const tag = el.tagName.toLowerCase();
|
|
952
|
+
const cls = el.className ? `.${String(el.className).split(/\s+/).filter(Boolean).slice(0, 2).join(".")}` : "";
|
|
953
|
+
return `<${tag}${el.id ? `#${el.id}` : ""}${cls}>`;
|
|
954
|
+
}
|
|
955
|
+
function candidatesAt(point) {
|
|
956
|
+
if (point.x < 0 || point.y < 0 || point.x > window.innerWidth || point.y > window.innerHeight) return [];
|
|
957
|
+
return Array.from(document.elementsFromPoint(point.x, point.y)).slice(0, 8).map((el) => ({
|
|
958
|
+
tag: el.tagName.toLowerCase(),
|
|
959
|
+
selector: selectorFor(el),
|
|
960
|
+
text: textFor(el),
|
|
961
|
+
rect: plainRect(el.getBoundingClientRect())
|
|
962
|
+
}));
|
|
963
|
+
}
|
|
964
|
+
function suggestionsFor(reason) {
|
|
965
|
+
if (reason === "covered") return ["点击点被其他元素覆盖,请关闭遮罩层、换用更精确 target,或确认后使用 force=true"];
|
|
966
|
+
if (reason === "not-in-viewport") return ["元素不在视口内,请先滚动到目标元素或改用可见元素定位"];
|
|
967
|
+
if (reason === "not-visible") return ["元素不可见,请等待页面渲染完成,或改用当前可见的元素定位"];
|
|
968
|
+
if (reason === "not-enabled") return ["元素被禁用,请等待 enabled 状态或检查表单前置条件"];
|
|
969
|
+
if (reason === "pointer-events-none") return ["元素设置了 pointer-events:none,请定位实际接收事件的子元素或父元素"];
|
|
970
|
+
return ["元素引用失效,请重新执行 extract type=\"state\" 获取新的 refId"];
|
|
971
|
+
}
|
|
972
|
+
function resolveElement(refId) {
|
|
973
|
+
return win.__mcpElementMap?.[refId]?.deref();
|
|
974
|
+
}
|
|
975
|
+
function check(refId) {
|
|
976
|
+
const element = resolveElement(refId);
|
|
977
|
+
if (!element || !element.isConnected) return {
|
|
978
|
+
actionable: false,
|
|
979
|
+
reason: "not-connected",
|
|
980
|
+
suggestions: suggestionsFor("not-connected")
|
|
981
|
+
};
|
|
982
|
+
const style = window.getComputedStyle(element);
|
|
983
|
+
const rect = element.getBoundingClientRect();
|
|
984
|
+
const clickPoint = {
|
|
985
|
+
x: rect.x + rect.width / 2,
|
|
986
|
+
y: rect.y + rect.height / 2
|
|
987
|
+
};
|
|
988
|
+
const failure = (reason, extra = {}) => ({
|
|
989
|
+
actionable: false,
|
|
990
|
+
reason,
|
|
991
|
+
rect: plainRect(rect),
|
|
992
|
+
clickPoint,
|
|
993
|
+
candidates: candidatesAt(clickPoint),
|
|
994
|
+
suggestions: suggestionsFor(reason),
|
|
995
|
+
...extra
|
|
996
|
+
});
|
|
997
|
+
if (typeof element.checkVisibility === "function" && !element.checkVisibility()) return failure("not-visible");
|
|
998
|
+
if (style.visibility !== "visible") return failure("not-visible");
|
|
999
|
+
if (style.display !== "contents" && rect.width === 0 && rect.height === 0) {
|
|
1000
|
+
if (!(element.querySelector("svg, canvas, img, video") !== null)) return failure("not-visible");
|
|
1001
|
+
}
|
|
1002
|
+
const htmlEl = element;
|
|
1003
|
+
if ("disabled" in htmlEl && htmlEl.disabled) return failure("not-enabled");
|
|
1004
|
+
let ancestor = element;
|
|
1005
|
+
while (ancestor) {
|
|
1006
|
+
if (ancestor.getAttribute("aria-disabled") === "true") return failure("not-enabled");
|
|
1007
|
+
ancestor = ancestor.parentElement;
|
|
1008
|
+
}
|
|
1009
|
+
if (style.pointerEvents === "none") return failure("pointer-events-none");
|
|
1010
|
+
const vw = window.innerWidth;
|
|
1011
|
+
const vh = window.innerHeight;
|
|
1012
|
+
if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) return failure("not-in-viewport");
|
|
1013
|
+
const hitEl = document.elementFromPoint(clickPoint.x, clickPoint.y);
|
|
1014
|
+
if (hitEl && hitEl !== element && !element.contains(hitEl) && !hitEl.contains(element)) return failure("covered", {
|
|
1015
|
+
coveringElement: describeElement(hitEl),
|
|
1016
|
+
coveringRect: plainRect(hitEl.getBoundingClientRect())
|
|
1017
|
+
});
|
|
1018
|
+
return {
|
|
1019
|
+
actionable: true,
|
|
1020
|
+
rect: plainRect(rect),
|
|
1021
|
+
clickPoint,
|
|
1022
|
+
candidates: candidatesAt(clickPoint)
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function scrollIntoViewWithRetry(refId) {
|
|
1026
|
+
const element = resolveElement(refId);
|
|
1027
|
+
if (!element || !element.isConnected) return {
|
|
1028
|
+
actionable: false,
|
|
1029
|
+
reason: "not-connected",
|
|
1030
|
+
suggestions: suggestionsFor("not-connected")
|
|
1031
|
+
};
|
|
1032
|
+
for (const alignment of [
|
|
1033
|
+
{
|
|
1034
|
+
block: "center",
|
|
1035
|
+
inline: "center",
|
|
1036
|
+
behavior: "instant"
|
|
1037
|
+
},
|
|
1038
|
+
{
|
|
1039
|
+
block: "end",
|
|
1040
|
+
inline: "end",
|
|
1041
|
+
behavior: "instant"
|
|
1042
|
+
},
|
|
1043
|
+
{
|
|
1044
|
+
block: "start",
|
|
1045
|
+
inline: "start",
|
|
1046
|
+
behavior: "instant"
|
|
1047
|
+
},
|
|
1048
|
+
{
|
|
1049
|
+
block: "nearest",
|
|
1050
|
+
inline: "nearest",
|
|
1051
|
+
behavior: "instant"
|
|
1052
|
+
}
|
|
1053
|
+
]) {
|
|
1054
|
+
element.scrollIntoView(alignment);
|
|
1055
|
+
const result = check(refId);
|
|
1056
|
+
if (result.actionable) return result;
|
|
1057
|
+
}
|
|
1058
|
+
return check(refId);
|
|
1059
|
+
}
|
|
1060
|
+
win.__mcpActionability = {
|
|
1061
|
+
check,
|
|
1062
|
+
scrollIntoViewWithRetry
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
function checkActionability(refId) {
|
|
1066
|
+
const helpers = window.__mcpActionability;
|
|
1067
|
+
if (!helpers) return {
|
|
1068
|
+
actionable: false,
|
|
1069
|
+
reason: "not-connected",
|
|
1070
|
+
suggestions: ["actionability helper 未安装,请重试当前操作"]
|
|
1071
|
+
};
|
|
1072
|
+
return helpers.check(refId);
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* 带 actionability 检查的点击(注入到页面执行)
|
|
1076
|
+
*
|
|
1077
|
+
* 流程:
|
|
1078
|
+
* 1. 检查可操作性
|
|
1079
|
+
* 2. 不在视口 → 滚动(4 种对齐轮换)
|
|
1080
|
+
* 3. 重新检查可操作性(滚动后坐标变化)
|
|
1081
|
+
* 4. 验证 hit target
|
|
1082
|
+
* 5. 执行点击
|
|
1083
|
+
*/
|
|
1084
|
+
function performActionableClick(refId, force) {
|
|
1085
|
+
const helpers = window.__mcpActionability;
|
|
1086
|
+
if (!helpers) return {
|
|
1087
|
+
success: false,
|
|
1088
|
+
error: "actionability helper 未安装,请重试当前操作",
|
|
1089
|
+
reason: "not-connected",
|
|
1090
|
+
suggestions: ["actionability helper 未安装,请重试当前操作"]
|
|
1091
|
+
};
|
|
1092
|
+
function dispatchClickSequence(el) {
|
|
1093
|
+
const rect = el.getBoundingClientRect();
|
|
1094
|
+
const opts = {
|
|
1095
|
+
bubbles: true,
|
|
1096
|
+
cancelable: true,
|
|
1097
|
+
button: 0,
|
|
1098
|
+
buttons: 1,
|
|
1099
|
+
clientX: Math.round(rect.x + rect.width / 2),
|
|
1100
|
+
clientY: Math.round(rect.y + rect.height / 2),
|
|
1101
|
+
view: window
|
|
1102
|
+
};
|
|
1103
|
+
el.dispatchEvent(new MouseEvent("mousedown", opts));
|
|
1104
|
+
el.focus();
|
|
1105
|
+
el.dispatchEvent(new MouseEvent("mouseup", {
|
|
1106
|
+
...opts,
|
|
1107
|
+
buttons: 0
|
|
1108
|
+
}));
|
|
1109
|
+
el.dispatchEvent(new MouseEvent("click", {
|
|
1110
|
+
...opts,
|
|
1111
|
+
buttons: 0
|
|
1112
|
+
}));
|
|
1113
|
+
}
|
|
1114
|
+
if (force) {
|
|
1115
|
+
const ref = window.__mcpElementMap?.[refId];
|
|
1116
|
+
if (!ref) return {
|
|
1117
|
+
success: false,
|
|
1118
|
+
error: `Element ${refId} not found`
|
|
1119
|
+
};
|
|
1120
|
+
const element = ref.deref();
|
|
1121
|
+
if (!element) return {
|
|
1122
|
+
success: false,
|
|
1123
|
+
error: `Element ${refId} no longer exists`
|
|
1124
|
+
};
|
|
1125
|
+
const el = element;
|
|
1126
|
+
el.focus();
|
|
1127
|
+
dispatchClickSequence(el);
|
|
1128
|
+
return { success: true };
|
|
1129
|
+
}
|
|
1130
|
+
let result = helpers.check(refId);
|
|
1131
|
+
if (!result.actionable && result.reason === "not-in-viewport") result = helpers.scrollIntoViewWithRetry(refId);
|
|
1132
|
+
if (!result.actionable) return {
|
|
1133
|
+
success: false,
|
|
1134
|
+
error: result.reason === "covered" ? `Element is covered by ${result.coveringElement}` : `Element is not actionable: ${result.reason}`,
|
|
1135
|
+
reason: result.reason,
|
|
1136
|
+
coveringElement: result.coveringElement,
|
|
1137
|
+
coveringRect: result.coveringRect,
|
|
1138
|
+
rect: result.rect,
|
|
1139
|
+
clickPoint: result.clickPoint,
|
|
1140
|
+
candidates: result.candidates,
|
|
1141
|
+
suggestions: result.suggestions
|
|
1142
|
+
};
|
|
1143
|
+
const element = (window.__mcpElementMap?.[refId])?.deref();
|
|
1144
|
+
if (!element) return {
|
|
1145
|
+
success: false,
|
|
1146
|
+
error: `Element ${refId} no longer exists`
|
|
1147
|
+
};
|
|
1148
|
+
const el = element;
|
|
1149
|
+
el.focus();
|
|
1150
|
+
dispatchClickSequence(el);
|
|
1151
|
+
return { success: true };
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* HTML5 drag 必须通过 DragEvent dispatchEvent 模拟(原生鼠标事件无法触发)
|
|
1155
|
+
* 在 MAIN 世界执行,refId 创建与消费侧均在 MAIN,共享 __mcpElementMap
|
|
1156
|
+
*/
|
|
1157
|
+
function performDragAndDrop(srcRefId, dstRefId) {
|
|
1158
|
+
const win = window;
|
|
1159
|
+
const srcRef = win.__mcpElementMap?.[srcRefId];
|
|
1160
|
+
const dstRef = win.__mcpElementMap?.[dstRefId];
|
|
1161
|
+
const src = srcRef?.deref();
|
|
1162
|
+
const dst = dstRef?.deref();
|
|
1163
|
+
if (!src) return {
|
|
1164
|
+
success: false,
|
|
1165
|
+
code: "REF_STALE",
|
|
1166
|
+
error: `drag 源元素 ${srcRefId} 不存在或已从 DOM 移除`
|
|
1167
|
+
};
|
|
1168
|
+
if (!dst) return {
|
|
1169
|
+
success: false,
|
|
1170
|
+
code: "REF_STALE",
|
|
1171
|
+
error: `drag 目标元素 ${dstRefId} 不存在或已从 DOM 移除`
|
|
1172
|
+
};
|
|
1173
|
+
const dt = new DataTransfer();
|
|
1174
|
+
src.dispatchEvent(new DragEvent("dragstart", {
|
|
1175
|
+
bubbles: true,
|
|
1176
|
+
cancelable: true,
|
|
1177
|
+
dataTransfer: dt
|
|
1178
|
+
}));
|
|
1179
|
+
dst.dispatchEvent(new DragEvent("dragenter", {
|
|
1180
|
+
bubbles: true,
|
|
1181
|
+
cancelable: true,
|
|
1182
|
+
dataTransfer: dt
|
|
1183
|
+
}));
|
|
1184
|
+
dst.dispatchEvent(new DragEvent("dragover", {
|
|
1185
|
+
bubbles: true,
|
|
1186
|
+
cancelable: true,
|
|
1187
|
+
dataTransfer: dt
|
|
1188
|
+
}));
|
|
1189
|
+
dst.dispatchEvent(new DragEvent("drop", {
|
|
1190
|
+
bubbles: true,
|
|
1191
|
+
cancelable: true,
|
|
1192
|
+
dataTransfer: dt
|
|
1193
|
+
}));
|
|
1194
|
+
src.dispatchEvent(new DragEvent("dragend", {
|
|
1195
|
+
bubbles: true,
|
|
1196
|
+
cancelable: true,
|
|
1197
|
+
dataTransfer: dt
|
|
1198
|
+
}));
|
|
1199
|
+
return { success: true };
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* 通过 nativeInputValueSetter 直接设置 value 并触发 input/change 事件
|
|
1203
|
+
* 兼容 React/Vue 等框架的受控组件(参考 Playwright fill())
|
|
1204
|
+
*/
|
|
1205
|
+
function dispatchInputToElement(refId, val) {
|
|
1206
|
+
const el = (window.__mcpElementMap?.[refId])?.deref();
|
|
1207
|
+
if (!el) return {
|
|
1208
|
+
success: false,
|
|
1209
|
+
error: `Element ${refId} not found`
|
|
1210
|
+
};
|
|
1211
|
+
el.focus();
|
|
1212
|
+
const proto = Object.getPrototypeOf(el);
|
|
1213
|
+
const setter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
|
|
1214
|
+
if (setter?.set) setter.set.call(el, val);
|
|
1215
|
+
else el.value = val;
|
|
1216
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
1217
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1218
|
+
return { success: true };
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* 获取元素的 computed style
|
|
1222
|
+
* prop = '*' 返回全部属性 JSON;否则返回指定属性值
|
|
1223
|
+
*/
|
|
1224
|
+
function getComputedStyleFromElement(refId, prop, expectedUrl) {
|
|
1225
|
+
if (expectedUrl != null && location.href !== expectedUrl) throw new Error("页面 URL 已变化,未读取");
|
|
1226
|
+
const el = (window.__mcpElementMap?.[refId])?.deref();
|
|
1227
|
+
if (!el) return null;
|
|
1228
|
+
const cs = window.getComputedStyle(el);
|
|
1229
|
+
if (prop === "*") {
|
|
1230
|
+
const obj = {};
|
|
1231
|
+
for (let i = 0; i < cs.length; i++) obj[cs[i]] = cs.getPropertyValue(cs[i]);
|
|
1232
|
+
return JSON.stringify(obj);
|
|
1233
|
+
}
|
|
1234
|
+
return cs.getPropertyValue(prop);
|
|
1235
|
+
}
|
|
1236
|
+
function inspectChallengePage(options) {
|
|
1237
|
+
const title = document.title || "";
|
|
1238
|
+
const url = location.href || "";
|
|
1239
|
+
const visibleBodyText = (document.body && document.body.innerText ? document.body.innerText : "").replace(/\s+/g, " ");
|
|
1240
|
+
const isVisible = (el) => {
|
|
1241
|
+
if (!el) return false;
|
|
1242
|
+
const style = window.getComputedStyle(el);
|
|
1243
|
+
if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
|
|
1244
|
+
const rect = el.getBoundingClientRect();
|
|
1245
|
+
return rect.width > 0 && rect.height > 0;
|
|
1246
|
+
};
|
|
1247
|
+
const bringIntoView = (el) => {
|
|
1248
|
+
if (!el || typeof el.scrollIntoView !== "function") return;
|
|
1249
|
+
el.scrollIntoView({
|
|
1250
|
+
block: "center",
|
|
1251
|
+
inline: "nearest",
|
|
1252
|
+
behavior: "instant"
|
|
1253
|
+
});
|
|
1254
|
+
};
|
|
1255
|
+
const hits = (selectors) => selectors.filter((selector) => {
|
|
1256
|
+
try {
|
|
1257
|
+
return Array.from(document.querySelectorAll(selector)).some(isVisible);
|
|
1258
|
+
} catch {
|
|
1259
|
+
return false;
|
|
1260
|
+
}
|
|
1261
|
+
});
|
|
1262
|
+
const isCloudflareFrame = (el) => {
|
|
1263
|
+
if (!el) return false;
|
|
1264
|
+
if (el.tagName.toUpperCase() === "IFRAME") {
|
|
1265
|
+
const src = String(el.getAttribute("src") || el.src || "");
|
|
1266
|
+
return src.includes("challenges.cloudflare.com") || src.includes("turnstile");
|
|
1267
|
+
}
|
|
1268
|
+
return Boolean(el.closest(options.frameSelectors.join(",")));
|
|
1269
|
+
};
|
|
1270
|
+
const selectorHits = hits(options.challengeSelectors);
|
|
1271
|
+
const deniedHits = hits(options.deniedSelectors);
|
|
1272
|
+
const widgetHits = hits(options.widgetSelectors);
|
|
1273
|
+
const frameHits = hits(options.frameSelectors);
|
|
1274
|
+
const cloudflareFramePresent = Array.from(document.querySelectorAll("iframe")).some((el) => isCloudflareFrame(el));
|
|
1275
|
+
const normalizedTitle = title.trim().toLowerCase().replace(/…/g, "...");
|
|
1276
|
+
const titlePending = options.titleNeedles.some((needle) => normalizedTitle.includes(String(needle).toLowerCase()));
|
|
1277
|
+
const textHits = options.textMarkers.filter((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
|
|
1278
|
+
const originResponsePending = options.originResponsePendingTextMarkers.some((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
|
|
1279
|
+
const interstitialPending = selectorHits.length > 0 || titlePending || textHits.length > 0;
|
|
1280
|
+
const findVisibleTurnstileBox = () => {
|
|
1281
|
+
const input = document.querySelector("input[name=\"cf-turnstile-response\"]");
|
|
1282
|
+
if (!input) return null;
|
|
1283
|
+
const candidates = [];
|
|
1284
|
+
let node = input.parentElement;
|
|
1285
|
+
while (node && node !== document.documentElement) {
|
|
1286
|
+
if (isVisible(node)) {
|
|
1287
|
+
const rect = node.getBoundingClientRect();
|
|
1288
|
+
if (rect.width >= 120 && rect.height >= 40) candidates.push(node);
|
|
1289
|
+
}
|
|
1290
|
+
node = node.parentElement;
|
|
1291
|
+
}
|
|
1292
|
+
if (candidates.length === 0) return null;
|
|
1293
|
+
return candidates.find((el) => {
|
|
1294
|
+
const rect = el.getBoundingClientRect();
|
|
1295
|
+
return rect.width >= 250 && rect.width <= 340 && rect.height >= 50 && rect.height <= 85;
|
|
1296
|
+
}) || candidates[0];
|
|
1297
|
+
};
|
|
1298
|
+
const hostVerify = Array.from(document.querySelectorAll(options.verifyButtonSelectors.join(","))).find(isVisible) || Array.from(document.querySelectorAll("button")).find((el) => {
|
|
1299
|
+
const text = (el.textContent || "").trim();
|
|
1300
|
+
return isVisible(el) && (text === "Verify you are human" || text === "请验证您是真人");
|
|
1301
|
+
});
|
|
1302
|
+
const turnstileBox = !originResponsePending && (interstitialPending || widgetHits.length > 0) ? findVisibleTurnstileBox() : null;
|
|
1303
|
+
const turnstilePresent = widgetHits.length > 0 || Boolean(hostVerify) || !originResponsePending && interstitialPending && (cloudflareFramePresent || frameHits.length > 0 || Boolean(turnstileBox));
|
|
1304
|
+
const useIframeClick = turnstilePresent && (cloudflareFramePresent || !hostVerify && interstitialPending && Boolean(document.querySelector("input[name=\"cf-turnstile-response\"]")));
|
|
1305
|
+
const pointFromRect = (rect, kind) => {
|
|
1306
|
+
if (!rect || rect.width < 8 || rect.height < 8) return null;
|
|
1307
|
+
const y = Math.round(rect.top + Math.min(rect.height, 65) / 2);
|
|
1308
|
+
if (kind === "verify") return {
|
|
1309
|
+
x: Math.round(rect.left + rect.width / 2),
|
|
1310
|
+
y
|
|
1311
|
+
};
|
|
1312
|
+
const widgetWidth = Math.min(rect.width, 300);
|
|
1313
|
+
return {
|
|
1314
|
+
x: Math.round(rect.left + Math.min(20, Math.max(14, widgetWidth / 15))),
|
|
1315
|
+
y
|
|
1316
|
+
};
|
|
1317
|
+
};
|
|
1318
|
+
let clickPoint = null;
|
|
1319
|
+
let clickTargetKind = null;
|
|
1320
|
+
let clickSource = null;
|
|
1321
|
+
const setClickTarget = (el, kind) => {
|
|
1322
|
+
if (!el) return;
|
|
1323
|
+
bringIntoView(el);
|
|
1324
|
+
const point = pointFromRect(el.getBoundingClientRect(), kind);
|
|
1325
|
+
if (!point) return;
|
|
1326
|
+
clickPoint = point;
|
|
1327
|
+
clickTargetKind = kind;
|
|
1328
|
+
clickSource = isCloudflareFrame(el) || useIframeClick ? "iframe" : "page";
|
|
1329
|
+
};
|
|
1330
|
+
if (hostVerify) setClickTarget(hostVerify, "verify");
|
|
1331
|
+
if (!clickPoint && turnstileBox) {
|
|
1332
|
+
const boxRect = turnstileBox.getBoundingClientRect();
|
|
1333
|
+
if (boxRect.width <= 340 && boxRect.height <= 85) setClickTarget(turnstileBox, "widget");
|
|
1334
|
+
}
|
|
1335
|
+
if (!clickPoint && turnstilePresent) {
|
|
1336
|
+
const frame = Array.from(document.querySelectorAll(options.frameSelectors.join(","))).find(isVisible);
|
|
1337
|
+
if (frame) setClickTarget(frame, "widget");
|
|
1338
|
+
}
|
|
1339
|
+
if (!clickPoint && turnstilePresent) {
|
|
1340
|
+
const widget = Array.from(document.querySelectorAll(options.widgetSelectors.join(","))).find(isVisible);
|
|
1341
|
+
if (widget) setClickTarget(widget, "widget");
|
|
1342
|
+
}
|
|
1343
|
+
if (!clickPoint && turnstileBox) setClickTarget(turnstileBox, "widget");
|
|
1344
|
+
const viewport = {
|
|
1345
|
+
screenX: Number(window.screenX),
|
|
1346
|
+
screenY: Number(window.screenY),
|
|
1347
|
+
innerWidth: Number(window.innerWidth),
|
|
1348
|
+
innerHeight: Number(window.innerHeight),
|
|
1349
|
+
outerWidth: Number(window.outerWidth),
|
|
1350
|
+
outerHeight: Number(window.outerHeight),
|
|
1351
|
+
devicePixelRatio: Number(window.devicePixelRatio || 1)
|
|
1352
|
+
};
|
|
1353
|
+
const horizontal = Math.max(0, viewport.outerWidth - viewport.innerWidth);
|
|
1354
|
+
const vertical = Math.max(0, viewport.outerHeight - viewport.innerHeight);
|
|
1355
|
+
const chromeLeft = Math.round(horizontal / 2);
|
|
1356
|
+
const chromeTop = Math.max(0, vertical - horizontal);
|
|
1357
|
+
const resolvedClickPoint = clickPoint;
|
|
1358
|
+
const screenPoint = resolvedClickPoint === null ? null : {
|
|
1359
|
+
x: Math.round(viewport.screenX + chromeLeft + resolvedClickPoint.x),
|
|
1360
|
+
y: Math.round(viewport.screenY + chromeTop + resolvedClickPoint.y)
|
|
1361
|
+
};
|
|
1362
|
+
return {
|
|
1363
|
+
title,
|
|
1364
|
+
url,
|
|
1365
|
+
selectorHits,
|
|
1366
|
+
deniedHits,
|
|
1367
|
+
textHits,
|
|
1368
|
+
originResponsePending,
|
|
1369
|
+
turnstilePresent,
|
|
1370
|
+
clickPoint: resolvedClickPoint,
|
|
1371
|
+
clickTargetKind,
|
|
1372
|
+
clickSource,
|
|
1373
|
+
screenPoint,
|
|
1374
|
+
viewport
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
//#endregion
|
|
1378
|
+
export { simulateMouseClick as C, simulateKeyboardType as S, performClick as _, extractHtml as a, performType as b, extractText as c, getComputedStyleFromElement as d, injectStealthScripts as f, performActionableClick as g, installFrameProbeListener as h, extractAttribute as i, findElements as l, installActionabilityHelpers as m, dispatchInputToElement as n, extractHtmlWithImages as o, inspectChallengePage as p, executeCode as r, extractMetadata as s, checkActionability as t, generateAccessibilityTree as u, performDragAndDrop as v, simulateMouseEvent as w, simulateKeyEvent as x, performScroll as y };
|