dsh-chrome-bridge 1.20.0 → 2.0.0
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.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +18 -8
- package/download.js +879 -60
- package/drag.js +38 -20
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +168 -16
- package/i18n/ru.js +168 -16
- package/i18n/zh.js +168 -16
- package/image-guard.js +13 -6
- package/index.js +17 -1155
- package/locale/ru.json +7 -0
- package/nav.js +43 -5
- package/package.json +8 -1
- package/panel.js +10 -1
- package/refs.js +275 -230
- package/setup.js +214 -46
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +223 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +361 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
package/refs.js
CHANGED
|
@@ -2,224 +2,43 @@
|
|
|
2
2
|
* 元素编号:browser_read(what=snapshot) 给页面上能点 / 能填的元素编上号 [N],
|
|
3
3
|
* 之后 browser_click / browser_input / browser_screenshot 直接传 ref=N,不用猜 CSS 选择器。
|
|
4
4
|
*
|
|
5
|
-
* 全在插件这一层做,只用宿主已有的 eval op —— 不改扩展。
|
|
6
|
-
* (改扩展得让用户去 chrome://extensions 重新加载;插件改了重启 DSH 就行。)
|
|
7
|
-
*
|
|
8
5
|
* 编号怎么记:
|
|
9
|
-
* ·
|
|
10
|
-
*
|
|
11
|
-
* ·
|
|
12
|
-
*
|
|
13
|
-
* · 跨站的 iframe 读不到里面(浏览器不让),只列一行提示
|
|
6
|
+
* · 用 window.__dshSnap.refs 的 WeakRef 和 ids 的反向记录核对元素身份
|
|
7
|
+
* · 仅当 [data-dsh-ref="N"] 命中同一元素时,才把它当作动作的选择器
|
|
8
|
+
* · shadow root、同源 iframe 或属性被替换时,按元素的整页视口坐标定位
|
|
9
|
+
* · 跨站 iframe 由扩展在隔离世界维护编号;旧扩展保留框架提示
|
|
14
10
|
* · 同一个元素再快照沿用旧编号(模型手里的旧编号继续有效);页面跳转后全部失效
|
|
15
11
|
*/
|
|
16
12
|
|
|
13
|
+
import { scanPage } from './vendor/extension/sw/frames.js'
|
|
14
|
+
import { frameField, isFrameRef, locateFrame, mergeFrameSnapshot, mergeFrameTexts } from './features/frames.js'
|
|
17
15
|
import { tt } from './i18n/index.js'
|
|
18
16
|
|
|
19
17
|
const ATTR = 'data-dsh-ref'
|
|
20
18
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const S = window.__dshSnap || (window.__dshSnap = { next: 1, shadow: new Map() });
|
|
24
|
-
const ATTR = ${JSON.stringify(ATTR)};
|
|
25
|
-
const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
26
|
-
const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
|
|
27
|
-
const q = (s) => JSON.stringify(s);
|
|
28
|
-
|
|
29
|
-
const root = ${scope ? `document.querySelector(${JSON.stringify(scope)})` : 'document.body'};
|
|
30
|
-
if (!root) return { error: 'scope' };
|
|
31
|
-
|
|
32
|
-
const TAGS = new Set(['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'SUMMARY']);
|
|
33
|
-
const ROLES = new Set(['button', 'link', 'checkbox', 'radio', 'switch', 'tab', 'menuitem', 'menuitemcheckbox',
|
|
34
|
-
'menuitemradio', 'option', 'combobox', 'textbox', 'searchbox', 'slider', 'spinbutton', 'treeitem', 'listbox']);
|
|
35
|
-
const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK']);
|
|
36
|
-
const FORM = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
|
|
37
|
-
|
|
38
|
-
// 框架里的元素按它自己那一页算样式
|
|
39
|
-
const css = (el) => (el.ownerDocument.defaultView || window).getComputedStyle(el);
|
|
40
|
-
const cursorOf = (el) => { try { return css(el).cursor } catch { return '' } };
|
|
41
|
-
const shown = (el, st) => {
|
|
42
|
-
const r = el.getBoundingClientRect();
|
|
43
|
-
if (r.width < 1 || r.height < 1) return false;
|
|
44
|
-
if (st.visibility === 'hidden') return false;
|
|
45
|
-
// 自定义样式的复选框常常把 <input> 设成透明叠在上面 —— 它照样接得住点击
|
|
46
|
-
if (!FORM.has(el.tagName) && Number(st.opacity) === 0) return false;
|
|
47
|
-
return true;
|
|
48
|
-
};
|
|
49
|
-
const interactive = (el, st) => {
|
|
50
|
-
const tag = el.tagName;
|
|
51
|
-
if (TAGS.has(tag)) {
|
|
52
|
-
if (tag === 'A') return el.hasAttribute('href') || el.hasAttribute('onclick');
|
|
53
|
-
if (tag === 'INPUT') return el.type !== 'hidden';
|
|
54
|
-
return true;
|
|
55
|
-
}
|
|
56
|
-
const role = (el.getAttribute('role') || '').split(' ')[0];
|
|
57
|
-
if (ROLES.has(role)) return true;
|
|
58
|
-
if (el.isContentEditable && !(el.parentElement && el.parentElement.isContentEditable)) return true;
|
|
59
|
-
if (el.hasAttribute('onclick')) return true;
|
|
60
|
-
if (el.getAttribute('tabindex') !== null && el.tabIndex >= 0 && role !== 'dialog') return true;
|
|
61
|
-
// 手搓的 <div> 按钮:认 cursor:pointer,但只认「从这里开始变成手型」的那一层,子元素继承的不算
|
|
62
|
-
if (st.cursor === 'pointer') {
|
|
63
|
-
const p = el.parentElement;
|
|
64
|
-
return !p || cursorOf(p) !== 'pointer';
|
|
65
|
-
}
|
|
66
|
-
return false;
|
|
67
|
-
};
|
|
68
|
-
const roleOf = (el) => {
|
|
69
|
-
const r = (el.getAttribute('role') || '').split(' ')[0];
|
|
70
|
-
if (r) return r;
|
|
71
|
-
const tag = el.tagName;
|
|
72
|
-
if (tag === 'A') return 'link';
|
|
73
|
-
if (tag === 'BUTTON' || tag === 'SUMMARY') return 'button';
|
|
74
|
-
if (tag === 'SELECT') return el.multiple ? 'listbox' : 'combobox';
|
|
75
|
-
if (tag === 'TEXTAREA') return 'textbox';
|
|
76
|
-
if (tag === 'INPUT') {
|
|
77
|
-
const t = (el.type || 'text').toLowerCase();
|
|
78
|
-
return ({ checkbox: 'checkbox', radio: 'radio', range: 'slider', file: 'file', button: 'button',
|
|
79
|
-
submit: 'button', reset: 'button', image: 'button', search: 'searchbox', number: 'spinbutton',
|
|
80
|
-
color: 'color', date: 'date', 'datetime-local': 'date', month: 'date', week: 'date', time: 'time' })[t] || 'textbox';
|
|
81
|
-
}
|
|
82
|
-
if (el.isContentEditable) return 'textbox';
|
|
83
|
-
return 'clickable';
|
|
84
|
-
};
|
|
85
|
-
const byId = (el, id) => {
|
|
86
|
-
const r = el.getRootNode();
|
|
87
|
-
return (r.getElementById && r.getElementById(id)) || document.getElementById(id);
|
|
88
|
-
};
|
|
89
|
-
const nameOf = (el) => {
|
|
90
|
-
const aria = norm(el.getAttribute('aria-label'));
|
|
91
|
-
if (aria) return aria;
|
|
92
|
-
const lb = el.getAttribute('aria-labelledby');
|
|
93
|
-
if (lb) {
|
|
94
|
-
const t = norm(lb.split(/\\s+/).map((id) => { const n = byId(el, id); return n ? n.innerText || n.textContent : ''; }).join(' '));
|
|
95
|
-
if (t) return t;
|
|
96
|
-
}
|
|
97
|
-
if (el.labels && el.labels.length) {
|
|
98
|
-
const t = norm([...el.labels].map((l) => l.innerText).join(' '));
|
|
99
|
-
if (t) return t;
|
|
100
|
-
}
|
|
101
|
-
if (el.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes(el.type)) return norm(el.value || el.type);
|
|
102
|
-
if (el.tagName === 'INPUT' && el.type === 'image') return norm(el.alt || el.title || 'image');
|
|
103
|
-
if (!FORM.has(el.tagName)) {
|
|
104
|
-
const t = norm(el.innerText);
|
|
105
|
-
if (t) return t;
|
|
106
|
-
const img = el.querySelector('img[alt]');
|
|
107
|
-
if (img && norm(img.alt)) return norm(img.alt);
|
|
108
|
-
const svgTitle = el.querySelector('svg title');
|
|
109
|
-
if (svgTitle && norm(svgTitle.textContent)) return norm(svgTitle.textContent);
|
|
110
|
-
}
|
|
111
|
-
return norm(el.getAttribute('title'));
|
|
112
|
-
};
|
|
113
|
-
const hrefOf = (el) => {
|
|
114
|
-
const h = el.getAttribute('href');
|
|
115
|
-
if (!h || h.startsWith('javascript:')) return '';
|
|
116
|
-
try {
|
|
117
|
-
const u = new URL(h, el.baseURI);
|
|
118
|
-
return u.origin === location.origin ? (u.pathname + u.search + u.hash) : (u.host + u.pathname);
|
|
119
|
-
} catch { return h; }
|
|
120
|
-
};
|
|
121
|
-
const stateOf = (el, role) => {
|
|
122
|
-
const out = [];
|
|
123
|
-
const tag = el.tagName;
|
|
124
|
-
if (tag === 'INPUT' && ['checkbox', 'radio'].includes(el.type)) { if (el.checked) out.push('已勾选'); }
|
|
125
|
-
else if (el.getAttribute('aria-checked') === 'true') out.push('已勾选');
|
|
126
|
-
if (el.getAttribute('aria-selected') === 'true') out.push('已选中');
|
|
127
|
-
const ex = el.getAttribute('aria-expanded');
|
|
128
|
-
if (ex === 'true') out.push('已展开'); else if (ex === 'false') out.push('已收起');
|
|
129
|
-
if (el.disabled || el.getAttribute('aria-disabled') === 'true') out.push('不可用');
|
|
130
|
-
if (el.readOnly) out.push('只读');
|
|
131
|
-
let extra = '';
|
|
132
|
-
if (tag === 'SELECT') {
|
|
133
|
-
const o = el.selectedOptions && el.selectedOptions[0];
|
|
134
|
-
extra = ' = ' + q(cut(norm(o ? o.textContent : ''), 40)) + '(' + el.options.length + ' 个选项)';
|
|
135
|
-
} else if (tag === 'INPUT' && el.type === 'password') {
|
|
136
|
-
if (el.value) extra = ' = ••••';
|
|
137
|
-
} else if ((tag === 'INPUT' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'image', 'file'].includes(el.type)) || tag === 'TEXTAREA') {
|
|
138
|
-
if (el.value) extra = ' = ' + q(cut(norm(el.value), 60));
|
|
139
|
-
} else if (role === 'textbox' && el.isContentEditable) {
|
|
140
|
-
const t = norm(el.innerText);
|
|
141
|
-
if (t) extra = ' = ' + q(cut(t, 60));
|
|
142
|
-
}
|
|
143
|
-
const ph = el.getAttribute('placeholder');
|
|
144
|
-
if (ph && !el.value) extra += ' 提示' + q(cut(norm(ph), 40));
|
|
145
|
-
if (tag === 'A') { const h = hrefOf(el); if (h) extra += ' → ' + cut(h, 70); }
|
|
146
|
-
return extra + (out.length ? ' (' + out.join(',') + ')' : '');
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
const seen = new Set();
|
|
150
|
-
const assign = (el) => {
|
|
151
|
-
let n = Number(el.getAttribute(ATTR)) || 0;
|
|
152
|
-
if (n && seen.has(n)) n = 0; // cloneNode 会把属性一起抄过去 —— 撞号就重新发
|
|
153
|
-
if (!n) { n = S.next++; el.setAttribute(ATTR, String(n)); }
|
|
154
|
-
seen.add(n);
|
|
155
|
-
if (el.getRootNode() !== document) S.shadow.set(n, new WeakRef(el));
|
|
156
|
-
return n;
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
const lines = [];
|
|
160
|
-
let count = 0, more = 0, scanned = 0;
|
|
161
|
-
const MAX = ${Number(maxItems) || 300};
|
|
162
|
-
const walk = (parent, depth = 0) => {
|
|
163
|
-
for (const el of parent.children) {
|
|
164
|
-
if (++scanned > 30000) return;
|
|
165
|
-
if (SKIP.has(el.tagName) || el.id === '__dsh_cursor__') continue;
|
|
166
|
-
let st;
|
|
167
|
-
try { st = css(el); } catch { continue; }
|
|
168
|
-
if (st.display === 'none') continue;
|
|
169
|
-
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
|
|
170
|
-
if (!shown(el, st)) continue;
|
|
171
|
-
const label = '[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '', 80);
|
|
172
|
-
let doc = null;
|
|
173
|
-
try { doc = el.contentDocument; } catch {}
|
|
174
|
-
if (doc && doc.body && depth < 5) {
|
|
175
|
-
lines.push(label + ' ↓');
|
|
176
|
-
walk(doc.body, depth + 1);
|
|
177
|
-
lines.push('[/iframe]');
|
|
178
|
-
} else {
|
|
179
|
-
lines.push(label + '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)');
|
|
180
|
-
}
|
|
181
|
-
continue;
|
|
182
|
-
}
|
|
183
|
-
const hm = /^H([1-3])$/.exec(el.tagName);
|
|
184
|
-
if (hm && shown(el, st)) {
|
|
185
|
-
const t = norm(el.innerText);
|
|
186
|
-
if (t) lines.push('#'.repeat(Number(hm[1])) + ' ' + cut(t, 80));
|
|
187
|
-
} else if (interactive(el, st) && shown(el, st)) {
|
|
188
|
-
if (count >= MAX) { more++; }
|
|
189
|
-
else {
|
|
190
|
-
const role = roleOf(el);
|
|
191
|
-
const name = nameOf(el);
|
|
192
|
-
lines.push('[' + assign(el) + '] ' + role + (name ? ' ' + q(cut(name, 80)) : '') + stateOf(el, role));
|
|
193
|
-
count++;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
if (el.tagName === 'SELECT' || el.tagName === 'svg') continue;
|
|
197
|
-
walk(el, depth);
|
|
198
|
-
if (el.shadowRoot) walk(el.shadowRoot, depth);
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
walk(root);
|
|
202
|
-
if (root.shadowRoot) walk(root.shadowRoot);
|
|
203
|
-
return { lines, count, more, scanned, title: document.title, url: location.href };
|
|
204
|
-
})()`
|
|
19
|
+
const SNAPSHOT_JS = (selector, scope, query) =>
|
|
20
|
+
`(${scanPage})(${JSON.stringify(selector)}, ${JSON.stringify(scope)}, ${JSON.stringify(query)}, null)`
|
|
205
21
|
|
|
206
22
|
/** 在页面里跑:编号 → 元素。普通元素给选择器;shadow 里的给坐标(顺带滚进视口)。 */
|
|
207
|
-
const LOCATE_JS = (ref, wantPoint) => `(async () => {
|
|
23
|
+
const LOCATE_JS = (ref, wantPoint, expectedDocId) => `(async () => {
|
|
208
24
|
const sel = ${JSON.stringify(`[${ATTR}="${ref}"]`)};
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
if (!el) {
|
|
212
|
-
const w = window.__dshSnap && window.__dshSnap.shadow.get(${Number(ref)});
|
|
213
|
-
el = w && w.deref();
|
|
214
|
-
shadow = true;
|
|
215
|
-
}
|
|
25
|
+
const getRef = () => ${refElementJs(ref, expectedDocId)};
|
|
26
|
+
const el = getRef();
|
|
216
27
|
// 框架跳转过的话,旧元素还「连着」它那份已经作废的文档:defaultView 没了就算失效
|
|
217
28
|
if (!el || !el.isConnected || !el.ownerDocument.defaultView) return { gone: true };
|
|
218
|
-
|
|
29
|
+
const shadow = el.getRootNode() !== document || document.querySelector(sel) !== el;
|
|
30
|
+
// 敏感输入不进入工具结果或光标名牌。
|
|
31
|
+
const masked = (${scanPage})(el, 'mask', el.ownerDocument.defaultView.getComputedStyle(el));
|
|
219
32
|
const out = { shadow, selector: shadow ? null : sel, tag: el.tagName.toLowerCase(),
|
|
220
|
-
text: (
|
|
33
|
+
text: (masked ? '••••' : el.innerText || el.value || el.getAttribute('aria-label') || '').replace(/\\s+/g, ' ').trim().slice(0, 60) };
|
|
221
34
|
if (!${wantPoint ? 'true' : 'false'} && !shadow) return out;
|
|
222
|
-
|
|
35
|
+
const point = await ${BOX_FN}(el);
|
|
36
|
+
if (getRef() !== el) return { gone: true };
|
|
37
|
+
if (!out.shadow && document.querySelector(sel) !== el) {
|
|
38
|
+
out.shadow = true;
|
|
39
|
+
out.selector = null;
|
|
40
|
+
}
|
|
41
|
+
return { ...out, ...point };
|
|
223
42
|
})()`
|
|
224
43
|
|
|
225
44
|
/**
|
|
@@ -244,12 +63,18 @@ const BOX_FN = `(async (el) => {
|
|
|
244
63
|
box: { x: left, y: top, width: r.width, height: r.height } };
|
|
245
64
|
})`
|
|
246
65
|
|
|
247
|
-
/**
|
|
248
|
-
export const refElementJs = (ref) => `(
|
|
249
|
-
const
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
66
|
+
/** 页内表达式:只信快照登记的元素,不从 DOM 属性反查编号。 */
|
|
67
|
+
export const refElementJs = (ref, expectedDocId) => `(() => {
|
|
68
|
+
const number = ${Number(ref)};
|
|
69
|
+
const state = window.__dshSnap;
|
|
70
|
+
if (${expectedDocId !== undefined} && state?.documentId !== ${JSON.stringify(expectedDocId)}) return null;
|
|
71
|
+
const el = state?.refs?.get(number)?.deref();
|
|
72
|
+
if (!el || !el.isConnected || !el.ownerDocument.defaultView || state.ids?.get(el) !== number) return null;
|
|
73
|
+
return el;
|
|
74
|
+
})()`
|
|
75
|
+
|
|
76
|
+
const tabDocs = new Map()
|
|
77
|
+
export const tabRefElementJs = (tabId, ref) => refElementJs(ref, tabDocs.get(tabId))
|
|
253
78
|
|
|
254
79
|
const goneError = (ref) => new Error(tt('err.refGone', { ref }))
|
|
255
80
|
|
|
@@ -257,20 +82,71 @@ const goneError = (ref) => new Error(tt('err.refGone', { ref }))
|
|
|
257
82
|
* 拍快照:返回给模型看的文本。
|
|
258
83
|
* @param call 与宿主通话的函数(index.js 的 call)
|
|
259
84
|
*/
|
|
260
|
-
|
|
261
|
-
|
|
85
|
+
const snapshotHistory = new Map()
|
|
86
|
+
const SNAPSHOT_CHARS = 8000
|
|
87
|
+
|
|
88
|
+
export async function snapshot(call, tabId, { selector, scope = 'all', diff = false, query = '', cursor = 0, limit = 300, maxItems } = {}) {
|
|
89
|
+
const key = JSON.stringify([tabId, selector || '', scope, query.trim().toLowerCase()])
|
|
90
|
+
const previous = snapshotHistory.get(key)
|
|
91
|
+
const r = await call('eval', { tabId, expression: SNAPSHOT_JS(selector, scope, query.trim().toLowerCase()), userGesture: false })
|
|
262
92
|
const v = r.value
|
|
263
93
|
if (!v) throw new Error(tt('err.snapshotFailed'))
|
|
264
94
|
if (v.error === 'scope') throw new Error(tt('err.noElement', { sel: selector }))
|
|
265
95
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
if (
|
|
271
|
-
|
|
272
|
-
|
|
96
|
+
await mergeFrameSnapshot(call, tabId, v, scope, query)
|
|
97
|
+
|
|
98
|
+
tabDocs.delete(tabId)
|
|
99
|
+
tabDocs.set(tabId, v.documentId)
|
|
100
|
+
if (tabDocs.size > 256) tabDocs.delete(tabDocs.keys().next().value)
|
|
101
|
+
|
|
102
|
+
const old = previous?.url === v.url && previous.documentId === v.documentId ? previous : null
|
|
103
|
+
const lines = new Map(v.rows.filter(({ ref }) => ref !== undefined).map(({ ref, line }) => [ref, line]))
|
|
104
|
+
let rows = v.rows.map(({ line }) => line)
|
|
105
|
+
let mode = ''
|
|
106
|
+
if (diff) {
|
|
107
|
+
if (old && cursor > 0 && old.diffPage) {
|
|
108
|
+
({ rows, mode } = old.diffPage)
|
|
109
|
+
} else if (old) {
|
|
110
|
+
rows = []
|
|
111
|
+
for (const [ref, line] of lines) {
|
|
112
|
+
if (!old.lines.has(ref)) rows.push(`[+] ${line}`)
|
|
113
|
+
else if (old.lines.get(ref) !== line) rows.push(`[~] ${line}`)
|
|
114
|
+
}
|
|
115
|
+
for (const [ref, line] of old.lines) if (!lines.has(ref)) rows.push(`[-] ${line}`)
|
|
116
|
+
mode = tt('res.snap.diff', { count: rows.length })
|
|
117
|
+
} else {
|
|
118
|
+
mode = tt('res.snap.full')
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const head = [v.title, v.url, tt('res.snap.head', { count: v.count }), mode].filter(Boolean).join('\n')
|
|
123
|
+
const page = []
|
|
124
|
+
let chars = head.length
|
|
125
|
+
const end = Math.min(rows.length, cursor + (maxItems ?? limit))
|
|
126
|
+
for (let i = cursor; i < end; i++) {
|
|
127
|
+
if (page.length && chars + rows[i].length + 1 > SNAPSHOT_CHARS) break
|
|
128
|
+
page.push(rows[i])
|
|
129
|
+
chars += rows[i].length + 1
|
|
130
|
+
}
|
|
131
|
+
const next = cursor + page.length
|
|
132
|
+
snapshotHistory.delete(key)
|
|
133
|
+
snapshotHistory.set(key, {
|
|
134
|
+
url: v.url,
|
|
135
|
+
documentId: v.documentId,
|
|
136
|
+
lines: cursor > 0 && old ? old.lines : lines,
|
|
137
|
+
diffPage: diff && next < rows.length ? { rows, mode } : null,
|
|
138
|
+
})
|
|
139
|
+
let cachedRows = [...snapshotHistory.values()].reduce((sum, entry) => sum + entry.lines.size + (entry.diffPage?.rows.length || 0), 0)
|
|
140
|
+
for (const [view, entry] of snapshotHistory) {
|
|
141
|
+
if (snapshotHistory.size === 1 || snapshotHistory.size <= 16 && cachedRows <= 60_000) break
|
|
142
|
+
cachedRows -= entry.lines.size + (entry.diffPage?.rows.length || 0)
|
|
143
|
+
snapshotHistory.delete(view)
|
|
273
144
|
}
|
|
145
|
+
const empty = diff && old ? tt('res.snap.noChanges') : tt('res.snap.nothing')
|
|
146
|
+
let text = `${head}\n\n${page.join('\n') || empty}`
|
|
147
|
+
if (next < rows.length) text += tt('res.snap.more', { more: rows.length - next, cursor: next })
|
|
148
|
+
if (v.outside) text += tt('res.snap.outside', { count: v.outside })
|
|
149
|
+
if (v.capped) text += tt('res.snap.scanCap')
|
|
274
150
|
return text
|
|
275
151
|
}
|
|
276
152
|
|
|
@@ -282,7 +158,8 @@ export async function snapshot(call, tabId, { selector, limit = 8000, maxItems =
|
|
|
282
158
|
export async function locate(call, tabId, ref, { wantPoint = false } = {}) {
|
|
283
159
|
const n = Number(ref)
|
|
284
160
|
if (!Number.isInteger(n) || n < 1) throw new Error(tt('err.refNotInt', { ref }))
|
|
285
|
-
|
|
161
|
+
if (isFrameRef(n)) return locateFrame(call, tabId, n)
|
|
162
|
+
const r = await call('eval', { tabId, expression: LOCATE_JS(n, wantPoint, tabDocs.get(tabId)), userGesture: false })
|
|
286
163
|
const v = r.value
|
|
287
164
|
if (!v || v.gone) throw goneError(n)
|
|
288
165
|
return v
|
|
@@ -309,15 +186,15 @@ export async function elementBox(call, tabId, { ref, selector }) {
|
|
|
309
186
|
return r.value
|
|
310
187
|
}
|
|
311
188
|
|
|
312
|
-
/**
|
|
189
|
+
/** 选择器无法定位时,直接聚焦快照记录的元素。 */
|
|
313
190
|
export async function focusShadow(call, tabId, ref) {
|
|
191
|
+
if (isFrameRef(ref)) return frameField(call, tabId, 'frameSetField', { ref, action: 'focus' })
|
|
314
192
|
const n = Number(ref)
|
|
315
193
|
const r = await call('eval', {
|
|
316
194
|
tabId,
|
|
317
195
|
expression: `(() => {
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
if (!el || !el.isConnected || !el.ownerDocument.defaultView) return null;
|
|
196
|
+
const el = ${tabRefElementJs(tabId, n)};
|
|
197
|
+
if (!el) return null;
|
|
321
198
|
el.focus();
|
|
322
199
|
return el.getRootNode().activeElement === el;
|
|
323
200
|
})()`,
|
|
@@ -328,16 +205,21 @@ export async function focusShadow(call, tabId, ref) {
|
|
|
328
205
|
|
|
329
206
|
/** shadow DOM / 框架里的下拉框:直接在页面里选(扩展的 select 只认 document.querySelector 找得到的)。 */
|
|
330
207
|
export async function selectInPage(call, tabId, ref, value) {
|
|
208
|
+
if (isFrameRef(ref)) return frameField(call, tabId, 'frameSelect', { ref, value: String(value) })
|
|
331
209
|
const n = Number(ref)
|
|
332
210
|
const r = await call('eval', {
|
|
333
211
|
tabId,
|
|
334
212
|
expression: `(() => {
|
|
335
|
-
const el = ${
|
|
213
|
+
const el = ${tabRefElementJs(tabId, n)};
|
|
336
214
|
if (!el) return null;
|
|
337
215
|
if (el.tagName !== 'SELECT') return { ok: false, why: ${JSON.stringify(tt('err.selectNotSelect'))} };
|
|
338
216
|
const v = ${JSON.stringify(String(value))};
|
|
339
217
|
const opts = [...el.options];
|
|
218
|
+
if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') {
|
|
219
|
+
return { ok: false, why: ${JSON.stringify(tt('err.fieldDisabled'))} };
|
|
220
|
+
}
|
|
340
221
|
const hit = opts.find((o) => o.value === v) || opts.find((o) => (o.textContent || '').trim() === v);
|
|
222
|
+
if (hit?.disabled || hit?.parentElement?.disabled) return { ok: false, why: ${JSON.stringify(tt('err.fieldDisabled'))} };
|
|
341
223
|
if (!hit) return { ok: false, why: ${JSON.stringify(tt('err.selectNoOption'))}, options: opts.map((o) => o.value).slice(0, 20) };
|
|
342
224
|
el.value = hit.value;
|
|
343
225
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
@@ -359,28 +241,191 @@ export async function selectInPage(call, tabId, ref, value) {
|
|
|
359
241
|
return v
|
|
360
242
|
}
|
|
361
243
|
|
|
362
|
-
/**
|
|
244
|
+
/** 按嵌套位置合并每个 iframe 的可见文字,旧版扩展保留跨站提示。 */
|
|
363
245
|
export async function frameTexts(call, tabId) {
|
|
364
246
|
const r = await call('eval', {
|
|
365
247
|
tabId,
|
|
366
248
|
expression: `(() => {
|
|
367
249
|
const out = [];
|
|
368
|
-
const walk = (doc, depth) => {
|
|
250
|
+
const walk = (doc, depth, path) => {
|
|
369
251
|
for (const f of doc.querySelectorAll('iframe, frame')) {
|
|
370
252
|
const b = f.getBoundingClientRect();
|
|
371
253
|
if (b.width < 2 || b.height < 2) continue;
|
|
372
254
|
const src = (f.getAttribute('src') || f.getAttribute('title') || f.getAttribute('name') || '').slice(0, 120);
|
|
255
|
+
const index = Array.prototype.indexOf.call(doc.defaultView.frames || [], f.contentWindow);
|
|
256
|
+
const childPath = [...path, index];
|
|
373
257
|
let d = null;
|
|
374
258
|
try { d = f.contentDocument; } catch {}
|
|
375
|
-
if (!d ||
|
|
259
|
+
if (!d?.body || d.defaultView?.origin !== doc.defaultView.origin) { out.push({ src, cross: true, path: childPath }); continue; }
|
|
376
260
|
out.push({ src, text: (d.body.innerText || '').trim() });
|
|
377
|
-
if (depth < 4) walk(d, depth + 1);
|
|
261
|
+
if (depth < 4) walk(d, depth + 1, childPath);
|
|
378
262
|
}
|
|
379
263
|
};
|
|
380
|
-
walk(document, 0);
|
|
264
|
+
walk(document, 0, []);
|
|
381
265
|
return out.slice(0, 30);
|
|
382
266
|
})()`,
|
|
383
267
|
userGesture: false,
|
|
384
268
|
})
|
|
385
|
-
|
|
269
|
+
const rows = Array.isArray(r.value) ? r.value : []
|
|
270
|
+
return mergeFrameTexts(call, tabId, rows)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const elementFor = (tabId, { ref, selector }) => ref != null ? tabRefElementJs(tabId, ref)
|
|
274
|
+
: selector ? `document.querySelector(${JSON.stringify(selector)})` : 'document.activeElement'
|
|
275
|
+
|
|
276
|
+
function missingTarget({ ref, selector }) {
|
|
277
|
+
return ref != null ? goneError(ref) : new Error(tt('err.noElement', { sel: selector || tt('res.input.active') }))
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function setField(call, tabId, args) {
|
|
281
|
+
const { action, checked, value } = args
|
|
282
|
+
if (action === 'select') return selectInPage(call, tabId, args.ref, value)
|
|
283
|
+
if (isFrameRef(args.ref)) return frameField(call, tabId, 'frameSetField', args)
|
|
284
|
+
const { value: result } = await call('eval', {
|
|
285
|
+
tabId,
|
|
286
|
+
userGesture: false,
|
|
287
|
+
expression: `(async () => {
|
|
288
|
+
const el = ${elementFor(tabId, args)};
|
|
289
|
+
if (!el || !el.isConnected) return null;
|
|
290
|
+
if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') return 'disabled';
|
|
291
|
+
if (${action === 'check'}) {
|
|
292
|
+
const desired = ${checked === true};
|
|
293
|
+
const native = el.tagName === 'INPUT' && ['checkbox', 'radio'].includes(el.type);
|
|
294
|
+
const custom = ['checkbox', 'switch', 'radio'].includes(el.getAttribute('role'));
|
|
295
|
+
if (!native && !custom) return 'wrong';
|
|
296
|
+
const state = () => native ? el.checked && !el.indeterminate : el.getAttribute('aria-checked') === 'true';
|
|
297
|
+
const mixed = native ? el.indeterminate : el.getAttribute('aria-checked') === 'mixed';
|
|
298
|
+
if (!mixed && state() === desired) return 'ok';
|
|
299
|
+
if (native && el.type === 'radio' && !desired) return 'wrong';
|
|
300
|
+
el.click();
|
|
301
|
+
await Promise.resolve();
|
|
302
|
+
return state() === desired && !(native && el.indeterminate) && el.getAttribute('aria-checked') !== 'mixed' ? 'ok' : 'rejected';
|
|
303
|
+
}
|
|
304
|
+
const view = el.ownerDocument.defaultView;
|
|
305
|
+
if (el.isContentEditable) return 'wrong';
|
|
306
|
+
const proto = el.tagName === 'TEXTAREA' ? view.HTMLTextAreaElement.prototype
|
|
307
|
+
: el.tagName === 'INPUT' && ['text', 'search', 'password', 'email', 'tel', 'url', 'number'].includes(el.type)
|
|
308
|
+
? view.HTMLInputElement.prototype : null;
|
|
309
|
+
if (!proto || el.readOnly || el.getAttribute('aria-readonly') === 'true') return 'wrong';
|
|
310
|
+
el.focus();
|
|
311
|
+
if (!el.isConnected) return null;
|
|
312
|
+
if (el.getRootNode().activeElement !== el) return 'wrong';
|
|
313
|
+
const value = ${JSON.stringify(String(value ?? ''))};
|
|
314
|
+
el.select();
|
|
315
|
+
Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value);
|
|
316
|
+
el.dispatchEvent(new view.Event('input', { bubbles: true, composed: true }));
|
|
317
|
+
el.dispatchEvent(new view.Event('change', { bubbles: true }));
|
|
318
|
+
await Promise.resolve();
|
|
319
|
+
if (!el.isConnected) return null;
|
|
320
|
+
if (el.value !== value) return 'rejected';
|
|
321
|
+
return 'ok';
|
|
322
|
+
})()`,
|
|
323
|
+
})
|
|
324
|
+
if (result == null) throw missingTarget(args)
|
|
325
|
+
if (result === 'disabled') throw new Error(tt('err.fieldDisabled'))
|
|
326
|
+
if (result === 'wrong') throw new Error(tt('err.fieldWrong'))
|
|
327
|
+
if (result !== 'ok') throw new Error(tt('err.fieldRejected'))
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export async function scrollElement(call, tabId, args) {
|
|
331
|
+
const dx = Number.isFinite(Number(args.dx)) ? Number(args.dx) : 0
|
|
332
|
+
const dy = Number.isFinite(Number(args.dy)) ? Number(args.dy) : 600
|
|
333
|
+
const r = await call('eval', {
|
|
334
|
+
tabId,
|
|
335
|
+
userGesture: false,
|
|
336
|
+
expression: `(() => {
|
|
337
|
+
const el = ${elementFor(tabId, args)};
|
|
338
|
+
if (!el) return null;
|
|
339
|
+
const view = el.ownerDocument.defaultView || window;
|
|
340
|
+
const scrollable = (n) => {
|
|
341
|
+
if (!n || n.nodeType !== 1) return false;
|
|
342
|
+
const canY = n.scrollHeight > n.clientHeight + 1;
|
|
343
|
+
const canX = n.scrollWidth > n.clientWidth + 1;
|
|
344
|
+
if (!canY && !canX) return false;
|
|
345
|
+
const st = view.getComputedStyle(n);
|
|
346
|
+
if (!st || (st.overflowY === undefined && st.overflowX === undefined)) return n === el;
|
|
347
|
+
return (canY && /auto|scroll|overlay/.test(st.overflowY)) || (canX && /auto|scroll|overlay/.test(st.overflowX));
|
|
348
|
+
};
|
|
349
|
+
let target = el;
|
|
350
|
+
if (!scrollable(target)) {
|
|
351
|
+
let cur = el.parentElement;
|
|
352
|
+
while (cur && !scrollable(cur)) cur = cur.parentElement;
|
|
353
|
+
target = cur || el.ownerDocument.scrollingElement || el.ownerDocument.documentElement || el;
|
|
354
|
+
}
|
|
355
|
+
target.scrollBy({ left: ${dx}, top: ${dy}, behavior: 'instant' });
|
|
356
|
+
return { scrollTop: Math.round(target.scrollTop), scrollHeight: target.scrollHeight };
|
|
357
|
+
})()`,
|
|
358
|
+
})
|
|
359
|
+
if (!r.value) throw missingTarget(args)
|
|
360
|
+
return r.value
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export async function readStructured(call, tabId, { what, selector, limit }) {
|
|
364
|
+
const { value } = await call('eval', {
|
|
365
|
+
tabId,
|
|
366
|
+
userGesture: false,
|
|
367
|
+
expression: `(() => {
|
|
368
|
+
const root = ${selector ? `document.querySelector(${JSON.stringify(selector)})`
|
|
369
|
+
: what === 'table' ? 'document.body' : "document.querySelector('main, [role=main]') || document.querySelector('article') || document.body"};
|
|
370
|
+
if (!root) return null;
|
|
371
|
+
const clean = (text) => String(text || '').replace(/\\s+/g, ' ').trim();
|
|
372
|
+
const visible = (el) => {
|
|
373
|
+
if (el.closest('script, style, noscript, template, [hidden], [aria-hidden=true]')) return false;
|
|
374
|
+
const style = el.ownerDocument.defaultView.getComputedStyle(el);
|
|
375
|
+
return style.visibility !== 'hidden' && (el.getClientRects().length > 0 || style.display === 'contents');
|
|
376
|
+
};
|
|
377
|
+
const max = ${Math.max(1, limit) + 1};
|
|
378
|
+
let out = '';
|
|
379
|
+
if (${what === 'table'}) {
|
|
380
|
+
const tables = root.tagName === 'TABLE' ? [root] : root.querySelectorAll('table');
|
|
381
|
+
for (const table of tables) {
|
|
382
|
+
if (!visible(table)) continue;
|
|
383
|
+
if (out) out += '\\n';
|
|
384
|
+
for (const row of table.rows) {
|
|
385
|
+
if (!visible(row)) continue;
|
|
386
|
+
out += Array.from(row.cells, (cell) => clean(cell.innerText || cell.textContent)).join('\\t') + '\\n';
|
|
387
|
+
if (out.length >= max) return out.slice(0, max);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return out.replace(/\\n+$/, '');
|
|
391
|
+
}
|
|
392
|
+
const escape = (s) => s.replace(/[\\\\*_\`\\[\\]<>]/g, (char) => '\\\\' + char);
|
|
393
|
+
const inline = (node) => {
|
|
394
|
+
if (node.nodeType === 3) return escape(node.nodeValue.replace(/\\s+/g, ' '));
|
|
395
|
+
if (node.nodeType !== 1 || !visible(node)) return '';
|
|
396
|
+
if (node.tagName === 'BR') return ' ';
|
|
397
|
+
const body = Array.from(node.childNodes, inline).join('');
|
|
398
|
+
if (node.tagName !== 'A' || !body.trim() || !node.hasAttribute('href')) return body;
|
|
399
|
+
try {
|
|
400
|
+
const url = new URL(node.getAttribute('href'), node.baseURI);
|
|
401
|
+
if (!['https:', 'http:', 'mailto:'].includes(url.protocol)) return body;
|
|
402
|
+
return '[' + body.trim() + '](<' + url.href.replace(/>/g, '%3E') + '>)';
|
|
403
|
+
} catch { return body; }
|
|
404
|
+
};
|
|
405
|
+
const append = (line) => { if (line && out.length < max) out += (out ? '\\n' : '') + line; };
|
|
406
|
+
const walk = (el, depth = 0) => {
|
|
407
|
+
if (out.length >= max || depth > 30 || !visible(el)) return;
|
|
408
|
+
if (/^H[1-6]$/.test(el.tagName)) append('#'.repeat(Number(el.tagName[1])) + ' ' + clean(inline(el)) + '\\n');
|
|
409
|
+
else if (['P', 'BLOCKQUOTE', 'A', 'PRE'].includes(el.tagName)) append(clean(inline(el)) + '\\n');
|
|
410
|
+
else if (['OL', 'UL'].includes(el.tagName)) {
|
|
411
|
+
let index = el.start || 1;
|
|
412
|
+
for (const item of el.children) {
|
|
413
|
+
if (out.length >= max) break;
|
|
414
|
+
if (item.tagName !== 'LI' || !visible(item)) continue;
|
|
415
|
+
const nodes = Array.from(item.childNodes);
|
|
416
|
+
const text = clean(nodes.filter((node) => !['OL', 'UL'].includes(node.tagName)).map(inline).join(''));
|
|
417
|
+
if (text) append(' '.repeat(depth) + (el.tagName === 'OL' ? index++ + '. ' : '- ') + text);
|
|
418
|
+
for (const node of nodes) if (['OL', 'UL'].includes(node.tagName)) walk(node, depth + 1);
|
|
419
|
+
}
|
|
420
|
+
if (!depth && out) out += '\\n';
|
|
421
|
+
} else {
|
|
422
|
+
for (const child of el.children) walk(child, depth);
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
walk(root);
|
|
426
|
+
return (out.trim() || clean(inline(root))).slice(0, max);
|
|
427
|
+
})()`,
|
|
428
|
+
})
|
|
429
|
+
if (value === null && selector) throw new Error(tt('err.noElement', { sel: selector }))
|
|
430
|
+
return value || ''
|
|
386
431
|
}
|