dsh-chrome-bridge 2.0.2 → 2.1.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 +1 -1
- package/README.md +1 -1
- package/core/ext.js +44 -15
- package/core/hosts.js +3 -4
- package/core/receipt.js +228 -31
- package/core/session.js +11 -14
- package/core/tooldef.js +10 -1
- package/core/transport.js +67 -17
- package/drag.js +118 -36
- package/features/frames.js +5 -2
- package/i18n/en.js +37 -7
- package/i18n/ru.js +37 -7
- package/i18n/zh.js +37 -7
- package/nav.js +103 -32
- package/package.json +1 -1
- package/refs.js +317 -77
- package/tools/batch.js +311 -0
- package/tools/click.js +37 -11
- package/tools/dialog.js +19 -2
- package/tools/drag.js +52 -9
- package/tools/fill.js +71 -22
- package/tools/index.js +3 -1
- package/tools/input.js +97 -36
- package/tools/nav.js +46 -23
- package/tools/read.js +2 -0
- package/tools/screenshot.js +10 -1
- package/tools/tabs.js +16 -2
- package/tools/wait.js +14 -6
- package/vendor/cb +3 -2
- package/vendor/extension/in-page-cursor.js +49 -11
- package/vendor/extension/manifest.json +1 -1
- package/vendor/extension/popup.css +1 -0
- package/vendor/extension/popup.html +6 -3
- package/vendor/extension/popup.js +19 -13
- package/vendor/extension/sw/actions.js +573 -0
- package/vendor/extension/sw/boot.js +7 -1
- package/vendor/extension/sw/cdp.js +219 -33
- package/vendor/extension/sw/conditions.js +176 -0
- package/vendor/extension/sw/confirm.js +39 -7
- package/vendor/extension/sw/cursor.js +534 -49
- package/vendor/extension/sw/dispatch.js +43 -8
- package/vendor/extension/sw/frames.js +643 -49
- package/vendor/extension/sw/imaging.js +35 -17
- package/vendor/extension/sw/lifecycle.js +82 -0
- package/vendor/extension/sw/ops.js +1028 -148
- package/vendor/extension/sw/page-access.js +292 -0
- package/vendor/extension/sw/popup-api.js +42 -10
- package/vendor/extension/sw/record.js +22 -5
- package/vendor/extension/sw/snapshot.js +251 -0
- package/vendor/extension/sw/state.js +24 -5
- package/vendor/extension/sw/tabui.js +10 -2
- package/vendor/in-page-cursor.js +49 -11
- package/vendor/skill/SKILL.md +8 -7
|
@@ -7,12 +7,18 @@ import {
|
|
|
7
7
|
withChooser,
|
|
8
8
|
} from './chooser.js'
|
|
9
9
|
import {
|
|
10
|
-
agentInput, clickPoint, cursorDo, cursorFx, cursorMove,
|
|
11
|
-
settle, unmountHandoff,
|
|
10
|
+
agentInput, agentInputKinds, bumpControlEpoch, clickPoint, cursorDo, cursorFx, cursorMove, injectCursor,
|
|
11
|
+
makeClickGuard, moveForAction, markCursor, mountHandoff, pressKey, RELEASED_MSG, settle, unmountHandoff,
|
|
12
12
|
} from './cursor.js'
|
|
13
13
|
import { areAllFramesAllowed, ensureUrlAllowed, hasProtectedSites, isUrlAllowed, loadProtectedSites } from './confirm.js'
|
|
14
|
+
import { waitCondition } from './conditions.js'
|
|
15
|
+
import { snapshotScan } from './snapshot.js'
|
|
16
|
+
import { act, dragGesture } from './actions.js'
|
|
17
|
+
import { waitPhase, watchLifecycle } from './lifecycle.js'
|
|
18
|
+
import { hashUrl, originOf, pageAccess, receiptOf, receiptState } from './page-access.js'
|
|
14
19
|
import { clickAndDownload } from './download.js'
|
|
15
|
-
import {
|
|
20
|
+
import { isSensitiveField, sensitiveValue } from './frames.js'
|
|
21
|
+
import { buildState, diagnostics, releaseAllTabs, setOwnWindow, setPaused, setShowCursor, setCursorPace } from './popup-api.js'
|
|
16
22
|
import { CHOOSER_TTL_MS, PAUSED_MSG, S } from './state.js'
|
|
17
23
|
import { labels, unmarkTab } from './tabui.js'
|
|
18
24
|
import { checkPath, isExtUrl, sleep, timeLeft, updateBadge, within } from './util.js'
|
|
@@ -50,7 +56,60 @@ async function protectedFilter(items, checkCurrentTab = true) {
|
|
|
50
56
|
return (x) => tabOk.get(x.tabId) === true && itemAllowed(x)
|
|
51
57
|
}
|
|
52
58
|
|
|
59
|
+
/** 为直调 CLI/旧插件动作补齐动态受保护 iframe 核验守卫,与 act() 共用同一防护语义 */
|
|
60
|
+
function resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, expectedNavGen) {
|
|
61
|
+
const id = Number(tabId)
|
|
62
|
+
const navCheck = Number.isInteger(expectedNavGen)
|
|
63
|
+
? () => {
|
|
64
|
+
if ((S.mainNavGeneration.get(id) || 0) !== expectedNavGen) {
|
|
65
|
+
throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
66
|
+
}
|
|
67
|
+
if (typeof check === 'function') check()
|
|
68
|
+
}
|
|
69
|
+
: check
|
|
70
|
+
const guard = makeClickGuard(tabId, dl, navCheck)
|
|
71
|
+
if (verifyFrames && verifyFramesOnly && pressCheck) {
|
|
72
|
+
return { guard, pGuard: makeClickGuard(tabId, dl, pressCheck), verifyFrames, verifyFramesOnly }
|
|
73
|
+
}
|
|
74
|
+
let frameGen = -1
|
|
75
|
+
let verifiedListEpoch = -1
|
|
76
|
+
const forbid = () => { throw new Error('USER_DENIED_SENSITIVE') }
|
|
77
|
+
const defaultVerifyFramesOnly = async () => {
|
|
78
|
+
if (!hasProtectedSites()) return
|
|
79
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
80
|
+
const targetGen = S.frameGeneration.get(id)
|
|
81
|
+
const listEpoch = S.protectedListEpoch
|
|
82
|
+
if (frameGen === targetGen && verifiedListEpoch === listEpoch) return
|
|
83
|
+
if (!await areAllFramesAllowed(id, false, true)) forbid()
|
|
84
|
+
if (S.frameGeneration.get(id) === targetGen && S.protectedListEpoch === listEpoch) {
|
|
85
|
+
frameGen = targetGen
|
|
86
|
+
verifiedListEpoch = listEpoch
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
forbid()
|
|
91
|
+
}
|
|
92
|
+
const defaultVerifyFrames = async () => {
|
|
93
|
+
guard()
|
|
94
|
+
await defaultVerifyFramesOnly()
|
|
95
|
+
guard()
|
|
96
|
+
}
|
|
97
|
+
const defaultPGuard = makeClickGuard(tabId, dl, () => {
|
|
98
|
+
guard()
|
|
99
|
+
const url = S.tabUrl.get(id)
|
|
100
|
+
if (isExtUrl(url) || (hasProtectedSites() && url && !isUrlAllowed(id, url))) forbid()
|
|
101
|
+
if (hasProtectedSites() && (frameGen !== S.frameGeneration.get(id) || verifiedListEpoch !== S.protectedListEpoch)) forbid()
|
|
102
|
+
})
|
|
103
|
+
return {
|
|
104
|
+
guard,
|
|
105
|
+
pGuard: pressCheck ? makeClickGuard(tabId, dl, pressCheck) : defaultPGuard,
|
|
106
|
+
verifyFrames: verifyFrames || defaultVerifyFrames,
|
|
107
|
+
verifyFramesOnly: verifyFramesOnly || defaultVerifyFramesOnly,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
53
111
|
const OPS = {
|
|
112
|
+
act, dragGesture, waitCondition, snapshotScan,
|
|
54
113
|
async diagnostics() {
|
|
55
114
|
const state = await buildState()
|
|
56
115
|
const { version, connected, paused, pauseReason, disconnectReason, attachedCount, showCursor, ownWindow, sessions } = state
|
|
@@ -93,21 +152,76 @@ const OPS = {
|
|
|
93
152
|
}
|
|
94
153
|
},
|
|
95
154
|
|
|
96
|
-
async networkIdle({ tabId, idleMs = 500, timeoutMs = 15000, urlFilter, since }) {
|
|
155
|
+
async networkIdle({ tabId, idleMs = 500, timeoutMs = 15000, urlFilter, since, receipt = false, controlEpoch, noReattach = false, expectedUrl, expectedUrlHash, expectedDocToken, expectedNavGen: reqNavGen }) {
|
|
97
156
|
const at = Date.now()
|
|
157
|
+
const deadline = at + timeoutMs
|
|
158
|
+
const rawId = Number(tabId)
|
|
159
|
+
const batchBound = expectedDocToken != null || expectedUrl != null || expectedUrlHash != null || Number.isInteger(reqNavGen)
|
|
160
|
+
if (noReattach && (S.paused || S.releasing.has(rawId) || !S.attached.has(rawId))) throw new Error(RELEASED_MSG)
|
|
98
161
|
const id = await within(ensure(tabId), timeoutMs, '等待网络超时')
|
|
162
|
+
const epoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0), globalEpoch = S.releaseAllEpoch
|
|
163
|
+
let expectedNavGen = Number.isInteger(reqNavGen) ? reqNavGen : undefined
|
|
164
|
+
const guard = () => {
|
|
165
|
+
if (S.paused || !S.attached.has(id) || S.releasing.has(id) ||
|
|
166
|
+
(S.controlEpoch.get(id) || 0) !== epoch || S.releaseAllEpoch !== globalEpoch) {
|
|
167
|
+
throw new Error('等待网络时浏览器控制中止')
|
|
168
|
+
}
|
|
169
|
+
if (expectedNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== expectedNavGen) {
|
|
170
|
+
throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
guard()
|
|
174
|
+
const needBefore = receipt || batchBound
|
|
175
|
+
if (batchBound && expectedNavGen === undefined) expectedNavGen = S.mainNavGeneration.get(id) || 0
|
|
176
|
+
const before = needBefore && await receiptState(id, deadline, guard)
|
|
177
|
+
if (batchBound) {
|
|
178
|
+
if (!before || before.reason || before.docToken == null ||
|
|
179
|
+
(S.mainNavGeneration.get(id) || 0) !== expectedNavGen ||
|
|
180
|
+
(expectedUrl && before.url !== expectedUrl) ||
|
|
181
|
+
(expectedUrlHash && hashUrl(before.url) !== expectedUrlHash) ||
|
|
182
|
+
(expectedDocToken != null && before.docToken !== expectedDocToken)) {
|
|
183
|
+
throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const finalize = async (out) => {
|
|
187
|
+
if (before) {
|
|
188
|
+
const after = await receiptState(id, Math.max(Date.now() + 500, deadline), guard, [], originOf(before.url), before.url)
|
|
189
|
+
guard()
|
|
190
|
+
if (batchBound && (after.reason === 'origin_changed' || after.docToken == null ||
|
|
191
|
+
(expectedUrl && after.url !== expectedUrl) ||
|
|
192
|
+
(expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
|
|
193
|
+
(expectedDocToken != null && after.docToken !== expectedDocToken))) {
|
|
194
|
+
throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
195
|
+
}
|
|
196
|
+
if (receipt) out.receipt = receiptOf(id, before, after)
|
|
197
|
+
}
|
|
198
|
+
return out
|
|
199
|
+
}
|
|
99
200
|
while (Date.now() - at < timeoutMs) {
|
|
100
|
-
|
|
201
|
+
guard()
|
|
101
202
|
const waitedMs = Date.now() - at
|
|
102
203
|
if (urlFilter) {
|
|
103
204
|
const hit = S.NET.find(r => r.tabId === id && r.at >= (since ?? at - 30000) && r.url.includes(urlFilter) && (!hasProtectedSites() || itemAllowed(r)))
|
|
104
|
-
if (hit) return { matched: true, url: hit.url, status: hit.status, method: hit.method, waitedMs }
|
|
205
|
+
if (hit) return finalize({ matched: true, url: hit.url, status: hit.status, method: hit.method, waitedMs })
|
|
105
206
|
} else {
|
|
106
207
|
const busy = [...S.netPending.values()].some(r => r.tabId === id && r.type !== 'WebSocket' && r.type !== 'EventSource')
|
|
107
|
-
if (!busy && Date.now() - Math.max(at, S.netChanged.get(id) || 0) >= idleMs)
|
|
208
|
+
if (!busy && Date.now() - Math.max(at, S.netChanged.get(id) || 0) >= idleMs) {
|
|
209
|
+
return finalize({ idle: true, waitedMs })
|
|
210
|
+
}
|
|
108
211
|
}
|
|
109
212
|
await sleep(Math.min(100, timeoutMs - waitedMs))
|
|
110
213
|
}
|
|
214
|
+
guard()
|
|
215
|
+
if (batchBound && before) {
|
|
216
|
+
const after = await receiptState(id, Date.now() + 500, guard, [], originOf(before.url), before.url)
|
|
217
|
+
guard()
|
|
218
|
+
if (after.reason === 'origin_changed' || after.docToken == null ||
|
|
219
|
+
(expectedUrl && after.url !== expectedUrl) ||
|
|
220
|
+
(expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
|
|
221
|
+
(expectedDocToken != null && after.docToken !== expectedDocToken)) {
|
|
222
|
+
throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
223
|
+
}
|
|
224
|
+
}
|
|
111
225
|
throw new Error('等待网络超时')
|
|
112
226
|
},
|
|
113
227
|
|
|
@@ -161,7 +275,8 @@ const OPS = {
|
|
|
161
275
|
},
|
|
162
276
|
|
|
163
277
|
async version() {
|
|
164
|
-
return { version: chrome.runtime.getManifest().version, id: chrome.runtime.id
|
|
278
|
+
return { version: chrome.runtime.getManifest().version, id: chrome.runtime.id,
|
|
279
|
+
caps: { actV1: true, navLifecycle: true, fastScroll: true, inPageWait: true, swDrag: true, snapshotV2: true, cursorPace: true } }
|
|
165
280
|
},
|
|
166
281
|
|
|
167
282
|
/**
|
|
@@ -169,12 +284,13 @@ const OPS = {
|
|
|
169
284
|
* 只开放「更安全」的方向:这条通道 DSH 里的模型也摸得到(cb / socket),
|
|
170
285
|
* 所以「恢复控制」不给 —— 那一下只能用户在 Chrome 的扩展面板里点。
|
|
171
286
|
*/
|
|
172
|
-
async panel({ action = 'state', on } = {}) {
|
|
287
|
+
async panel({ action = 'state', on, cursorPace } = {}) {
|
|
173
288
|
if (action === 'pause') {
|
|
174
289
|
if (!on) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 面板里打开')
|
|
175
290
|
await setPaused(true, 'panel')
|
|
176
291
|
} else if (action === 'cursor') {
|
|
177
|
-
await
|
|
292
|
+
if (cursorPace !== undefined) await setCursorPace(cursorPace, 'DSH 设置页')
|
|
293
|
+
else await setShowCursor(!!on, 'DSH 设置页')
|
|
178
294
|
} else if (action === 'window') {
|
|
179
295
|
await setOwnWindow(!!on, 'DSH 设置页')
|
|
180
296
|
} else if (action === 'releaseAll') {
|
|
@@ -184,7 +300,7 @@ const OPS = {
|
|
|
184
300
|
}
|
|
185
301
|
const st = await buildState()
|
|
186
302
|
return {
|
|
187
|
-
version: st.version, id: chrome.runtime.id, paused: st.paused, showCursor: st.showCursor,
|
|
303
|
+
version: st.version, id: chrome.runtime.id, paused: st.paused, showCursor: st.showCursor, cursorPace: st.cursorPace,
|
|
188
304
|
ownWindow: st.ownWindow, attachedCount: st.attachedCount, pauseReason: st.pauseReason, handoff: st.handoff,
|
|
189
305
|
protectedCount: Array.isArray(st.protectedSites) ? st.protectedSites.length : 0,
|
|
190
306
|
sessions: st.sessions.filter((x) => x.tabs.some((t) => t.attached)).length,
|
|
@@ -246,19 +362,28 @@ const OPS = {
|
|
|
246
362
|
|
|
247
363
|
/** 第二个参数只给扩展内部用(dispatch 只传 args):空闲自动断开传 reason 'idle',受保护网站的放行就不跟着作废 */
|
|
248
364
|
async detach({ tabId }, { reason = 'detached' } = {}) {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
365
|
+
const id = Number(tabId)
|
|
366
|
+
if (reason !== 'idle') {
|
|
367
|
+
S.releasing.add(id)
|
|
368
|
+
bumpControlEpoch(id)
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
if (S.activeDownload?.tabId === id) {
|
|
372
|
+
S.activeDownload.interrupt()
|
|
373
|
+
await S.activeDownload.cleaned
|
|
374
|
+
}
|
|
375
|
+
S.ensureInflight.delete(id)
|
|
376
|
+
clearPending(id)
|
|
377
|
+
S.dialogs.delete(id)
|
|
378
|
+
failLoadWaiter(id, '等页面加载时被松手了') // 自己 detach 不会触发 onDetach,这里补上
|
|
379
|
+
try { await chrome.debugger.detach({ tabId: id }) } catch {}
|
|
380
|
+
forgetAttached(id, reason === 'idle' ? 'idle' : 'detached')
|
|
381
|
+
S.lastUsed.delete(id)
|
|
382
|
+
await unmarkTab(tabId)
|
|
383
|
+
return { tabId: id, attached: false }
|
|
384
|
+
} finally {
|
|
385
|
+
S.releasing.delete(id)
|
|
252
386
|
}
|
|
253
|
-
S.ensureInflight.delete(Number(tabId))
|
|
254
|
-
clearPending(Number(tabId))
|
|
255
|
-
S.dialogs.delete(Number(tabId))
|
|
256
|
-
failLoadWaiter(Number(tabId), '等页面加载时被松手了') // 自己 detach 不会触发 onDetach,这里补上
|
|
257
|
-
try { await chrome.debugger.detach({ tabId: Number(tabId) }) } catch {}
|
|
258
|
-
forgetAttached(Number(tabId), reason === 'idle' ? 'idle' : 'detached')
|
|
259
|
-
S.lastUsed.delete(Number(tabId))
|
|
260
|
-
await unmarkTab(tabId)
|
|
261
|
-
return { tabId: Number(tabId), attached: false }
|
|
262
387
|
},
|
|
263
388
|
|
|
264
389
|
async activate({ tabId }) {
|
|
@@ -268,17 +393,105 @@ const OPS = {
|
|
|
268
393
|
return { tabId: Number(tabId), windowId: t.windowId }
|
|
269
394
|
},
|
|
270
395
|
|
|
271
|
-
async open({ url, active = false }) {
|
|
396
|
+
async open({ url, active = false, wait = 'none', timeoutMs = 30000, receipt = false }) {
|
|
397
|
+
const phase = waitPhase(wait)
|
|
398
|
+
const deadline = Date.now() + timeoutMs
|
|
272
399
|
// 相对地址会被 tabs.create 按扩展自己的地址补全(example.com → chrome-extension://…/example.com),只收完整网址
|
|
273
400
|
if (url) { try { new URL(url) } catch { throw new Error(`要给完整网址(带 https://):${url}`) } }
|
|
274
401
|
// 默认开进 DSH 自己的窗口(后台,不抢焦点);用户关了「单独窗口」就在当前窗口后台开页。
|
|
275
402
|
// 两种都不顶掉用户正在看的标签页。active=true(cb open --front)是有意要它跳到眼前,照旧开在当前窗口
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
403
|
+
const own = S.ownWindow && !active
|
|
404
|
+
const waited = !!url && phase !== 'none'
|
|
405
|
+
const dest = waited ? 'about:blank' : url
|
|
406
|
+
const t = own ? await openInAgentWindow(dest) : await chrome.tabs.create({ url: dest, active: !!active })
|
|
407
|
+
const out = own ? { tabId: t.id, url: t.pendingUrl || t.url || url || '', window: 'agent' } : { tabId: t.id, url: t.url }
|
|
408
|
+
if (waited) {
|
|
409
|
+
const startEpoch = S.controlEpoch.get(t.id) || 0, startReleaseAll = S.releaseAllEpoch
|
|
410
|
+
try {
|
|
411
|
+
Object.assign(out, await OPS.nav({ tabId: t.id, url, wait: phase, timeoutMs: timeLeft(deadline) }), { window: own ? 'agent' : 'current' })
|
|
412
|
+
} catch (err) {
|
|
413
|
+
const isInterrupted = () => S.paused || S.releasing.has(t.id) || S.releaseAllEpoch !== startReleaseAll ||
|
|
414
|
+
(S.controlEpoch.get(t.id) || 0) !== startEpoch || /放开|松手|暂停|USER_ACTIVE/.test(String(err?.message || ''))
|
|
415
|
+
const live = (isInterrupted() || typeof chrome.tabs?.get !== 'function') ? null : await chrome.tabs.get(t.id).catch(() => null)
|
|
416
|
+
const liveUrl = typeof live?.url === 'string' ? live.url : ''
|
|
417
|
+
const livePending = typeof live?.pendingUrl === 'string' ? live.pendingUrl : ''
|
|
418
|
+
const pendingBelongsToUs = !livePending || livePending === 'about:blank' || livePending === url
|
|
419
|
+
const stillBlank = !isInterrupted() && live && pendingBelongsToUs && (liveUrl === 'about:blank' || liveUrl.startsWith('chrome-error://'))
|
|
420
|
+
if (stillBlank) await chrome.tabs.remove(t.id).catch(() => {})
|
|
421
|
+
throw err
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const reqOrigin = originOf(url || '')
|
|
425
|
+
const checkOrigin = receipt || waited || Boolean(reqOrigin)
|
|
426
|
+
if (checkOrigin) {
|
|
427
|
+
const epoch = S.controlEpoch.get(t.id) || 0, globalEpoch = S.releaseAllEpoch
|
|
428
|
+
const guard = () => {
|
|
429
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
430
|
+
if (S.releasing.has(t.id) || (S.controlEpoch.get(t.id) || 0) !== epoch || globalEpoch !== S.releaseAllEpoch) throw new Error(RELEASED_MSG)
|
|
431
|
+
}
|
|
432
|
+
if (receipt) guard()
|
|
433
|
+
const hasTabsGet = typeof chrome.tabs?.get === 'function'
|
|
434
|
+
if (!hasTabsGet && receipt) {
|
|
435
|
+
out.receipt = {
|
|
436
|
+
beforeUrl: url || '', beforeTitle: '', url: out.url || url || '', title: '',
|
|
437
|
+
navigated: waited, originChanged: false, protectedSite: false, pendingDialog: null,
|
|
438
|
+
liveUpdate: null, unverified: true, controlEpoch: S.controlEpoch.get(t.id) || 0,
|
|
439
|
+
navGeneration: S.mainNavGeneration.get(t.id) || 0,
|
|
440
|
+
}
|
|
441
|
+
return out
|
|
442
|
+
}
|
|
443
|
+
const landed = hasTabsGet
|
|
444
|
+
? await pageAccess(t.id, { frames: false })
|
|
445
|
+
: { url: t.pendingUrl || t.url || '', committedUrl: t.url || '', committedSameOrigin: false, title: '' }
|
|
446
|
+
const landedOrigin = originOf(landed.url)
|
|
447
|
+
const committedOrigin = originOf(landed.committedUrl || '')
|
|
448
|
+
const committedMismatch = Boolean(reqOrigin) && Boolean(committedOrigin) && committedOrigin !== reqOrigin
|
|
449
|
+
const notYetStarted = !waited && !landed.reason && (!landed.url || landed.url === 'about:blank') && !committedMismatch
|
|
450
|
+
const unexpectedCross = !notYetStarted && (landed.reason === 'protected' || (Boolean(reqOrigin) && (!landedOrigin || reqOrigin !== landedOrigin)))
|
|
451
|
+
let after = notYetStarted
|
|
452
|
+
? { url: url || '', committedUrl: '', committedSameOrigin: false, title: '', live: [], secrets: [] }
|
|
453
|
+
: unexpectedCross
|
|
454
|
+
? { url: landedOrigin, committedUrl: landed.committedUrl || '', committedSameOrigin: Boolean(landed.committedSameOrigin), title: '', live: [], secrets: [], ...(landed.reason && { reason: landed.reason }) }
|
|
455
|
+
: committedMismatch
|
|
456
|
+
? { url: landedOrigin || reqOrigin, committedUrl: landed.committedUrl, committedSameOrigin: false, title: '', live: [], secrets: [] }
|
|
457
|
+
: (receipt ? await receiptState(t.id, deadline, guard, [], reqOrigin || undefined, url || undefined) : landed)
|
|
458
|
+
if (receipt) guard()
|
|
459
|
+
const finalOrigin = originOf(after.url)
|
|
460
|
+
const finalCommittedOrigin = originOf(after.committedUrl || '')
|
|
461
|
+
const finalCommittedMismatch = Boolean(reqOrigin) && Boolean(finalCommittedOrigin) && finalCommittedOrigin !== reqOrigin
|
|
462
|
+
const finalCross = !notYetStarted && (unexpectedCross || after.reason === 'protected' || after.reason === 'origin_changed' ||
|
|
463
|
+
(Boolean(reqOrigin) && (!finalOrigin || reqOrigin !== finalOrigin)))
|
|
464
|
+
if (finalCross) {
|
|
465
|
+
after = { url: finalOrigin, committedUrl: after.committedUrl || '', committedSameOrigin: Boolean(after.committedSameOrigin), title: '', live: [], secrets: [], ...(after.reason && { reason: after.reason }) }
|
|
466
|
+
} else if (finalCommittedMismatch) {
|
|
467
|
+
after = { ...after, url: finalOrigin || reqOrigin, committedSameOrigin: false, title: '', live: [], secrets: [] }
|
|
468
|
+
}
|
|
469
|
+
if (receipt) {
|
|
470
|
+
const baseline = { url: url || '', title: '', live: [] }
|
|
471
|
+
out.receipt = receiptOf(t.id, baseline, after, undefined, [], !finalCross && !finalCommittedMismatch)
|
|
472
|
+
if (finalCross || finalCommittedMismatch) {
|
|
473
|
+
out.receipt.url = finalCross ? finalOrigin : (finalOrigin || reqOrigin)
|
|
474
|
+
out.receipt.title = ''
|
|
475
|
+
out.receipt.liveUpdate = null
|
|
476
|
+
if (finalCross) out.receipt.originChanged = true
|
|
477
|
+
if (out.receipt.pendingDialog) {
|
|
478
|
+
out.receipt.pendingDialog = (!after.committedSameOrigin || finalCommittedMismatch)
|
|
479
|
+
? null : { ...out.receipt.pendingDialog, message: '' }
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (out.receipt.protectedSite && hasProtectedSites() && !isUrlAllowed(t.id, baseline.url)) {
|
|
483
|
+
try { out.receipt.beforeUrl = new URL(baseline.url).origin } catch { out.receipt.beforeUrl = '' }
|
|
484
|
+
}
|
|
485
|
+
out.url = out.receipt.url
|
|
486
|
+
out.title = out.receipt.title
|
|
487
|
+
if (out.receipt.protectedSite) out.protectedSite = true
|
|
488
|
+
} else if (finalCross || finalCommittedMismatch) {
|
|
489
|
+
out.url = finalCross ? finalOrigin : (finalOrigin || reqOrigin)
|
|
490
|
+
out.title = ''
|
|
491
|
+
if (after.reason === 'protected') out.protectedSite = true
|
|
492
|
+
}
|
|
279
493
|
}
|
|
280
|
-
|
|
281
|
-
return { tabId: t.id, url: t.url }
|
|
494
|
+
return out
|
|
282
495
|
},
|
|
283
496
|
|
|
284
497
|
async close({ tabId }) {
|
|
@@ -286,26 +499,62 @@ const OPS = {
|
|
|
286
499
|
return { closed: Number(tabId) }
|
|
287
500
|
},
|
|
288
501
|
|
|
289
|
-
async eval({ tabId, expression, userGesture = false, timeoutMs }) {
|
|
290
|
-
|
|
502
|
+
async eval({ tabId, expression, userGesture = false, timeoutMs, controlEpoch, requireControl = false, noReattach = false }) {
|
|
503
|
+
const id = Number(tabId)
|
|
504
|
+
const startEpoch = S.controlEpoch.get(id) || 0
|
|
505
|
+
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
506
|
+
const check = (Number.isInteger(controlEpoch) || requireControl || noReattach)
|
|
507
|
+
? makeClickGuard(tabId, dl, () => {
|
|
508
|
+
if (noReattach && !S.attached.has(id)) throw new Error(RELEASED_MSG)
|
|
509
|
+
if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
|
|
510
|
+
if (requireControl && (S.controlEpoch.get(id) || 0) !== startEpoch) throw new Error(RELEASED_MSG)
|
|
511
|
+
})
|
|
512
|
+
: undefined
|
|
513
|
+
if (check) check()
|
|
514
|
+
const value = await evaluate(tabId, expression, userGesture === true, timeoutMs, check)
|
|
515
|
+
if ((requireControl || noReattach) && check) check()
|
|
516
|
+
return { value, controlEpoch: startEpoch, navGeneration: S.mainNavGeneration.get(id) || 0 }
|
|
291
517
|
},
|
|
292
518
|
|
|
293
|
-
async cdp({ tabId, method, params, timeoutMs }) {
|
|
519
|
+
async cdp({ tabId, method, params, timeoutMs, controlEpoch, noReattach = false, releaseOnlyForAttachSeq }) {
|
|
520
|
+
const id = Number(tabId)
|
|
521
|
+
if (Number.isInteger(releaseOnlyForAttachSeq) && method === 'Input.dispatchMouseEvent' && params?.type === 'mouseReleased') {
|
|
522
|
+
const startReleaseAll = S.releaseAllEpoch
|
|
523
|
+
const startEpoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0)
|
|
524
|
+
const sessionOk = () => S.attached.has(id) && S.attachSeq.get(id) === releaseOnlyForAttachSeq &&
|
|
525
|
+
!S.releasing.has(id) && !S.paused && S.releaseAllEpoch === startReleaseAll &&
|
|
526
|
+
(S.controlEpoch.get(id) || 0) === startEpoch
|
|
527
|
+
if (!sessionOk()) return { result: {}, skipped: true }
|
|
528
|
+
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
529
|
+
const fg = resolveFrameGuards(tabId, dl)
|
|
530
|
+
await (dl !== undefined ? within(fg.verifyFramesOnly(), timeLeft(dl), '检查受保护网站超时') : fg.verifyFramesOnly())
|
|
531
|
+
if (!sessionOk()) return { result: {}, skipped: true }
|
|
532
|
+
const url = S.tabUrl.get(id)
|
|
533
|
+
if (isExtUrl(url) || (hasProtectedSites() && url && !isUrlAllowed(id, url))) throw new Error('USER_DENIED_SENSITIVE')
|
|
534
|
+
const r = await chrome.debugger.sendCommand({ tabId: id }, method, params || {})
|
|
535
|
+
return { result: r, attachSeq: S.attachSeq.get(id) || 0, controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
536
|
+
}
|
|
537
|
+
const check = (Number.isInteger(controlEpoch) || noReattach)
|
|
538
|
+
? () => {
|
|
539
|
+
if (noReattach && (S.paused || S.releasing.has(id) || !S.attached.has(id))) throw new Error(RELEASED_MSG)
|
|
540
|
+
if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
|
|
541
|
+
}
|
|
542
|
+
: undefined
|
|
543
|
+
if (check) check()
|
|
294
544
|
checkCdp(method, params)
|
|
295
545
|
if (method === 'Network.getCookies') {
|
|
296
|
-
const current = new URL((await chrome.tabs.get(
|
|
546
|
+
const current = new URL((await chrome.tabs.get(id)).url)
|
|
297
547
|
if (!['http:', 'https:'].includes(current.protocol) || params.urls.some(url => new URL(url).hostname !== current.hostname))
|
|
298
548
|
throw new Error('Network.getCookies urls 必须与当前页同主机')
|
|
299
549
|
}
|
|
300
550
|
if (method === 'Page.navigateToHistoryEntry') {
|
|
301
551
|
// 后退 / 前进到历史里的扩展页面也算「导航到扩展页面」
|
|
302
|
-
const h = await send(tabId, 'Page.getNavigationHistory', {}, timeoutMs)
|
|
552
|
+
const h = await send(tabId, 'Page.getNavigationHistory', {}, timeoutMs, check)
|
|
303
553
|
const e = (h.entries || []).find((x) => x.id === (params || {}).entryId)
|
|
304
554
|
if (e && isExtUrl(e.url)) throw new Error('扩展页面(chrome-extension://)不能被自动化操作')
|
|
305
555
|
}
|
|
306
556
|
if (method === 'Network.getResponseBody' && hasProtectedSites()) {
|
|
307
557
|
// 响应体可能是别的标签页 / 别的网站 / 受保护站重定向到 CDN 的接口:核对整条重定向链 + 发起页面来源
|
|
308
|
-
const id = Number(tabId)
|
|
309
558
|
const rid = params?.requestId
|
|
310
559
|
const rec = rid == null ? null
|
|
311
560
|
: S.netPending.get(`${id}/${rid}`) || S.NET.findLast((n) => n.tabId === id && n.id === rid)
|
|
@@ -316,56 +565,173 @@ const OPS = {
|
|
|
316
565
|
if (!isUrlAllowed(id, u)) await ensureUrlAllowed(id, u, { op: 'cdp' })
|
|
317
566
|
}
|
|
318
567
|
}
|
|
319
|
-
const
|
|
320
|
-
|
|
568
|
+
const meta = {}
|
|
569
|
+
if (typeof method === 'string' && method.startsWith('Input.')) {
|
|
570
|
+
const fg = resolveFrameGuards(tabId, timeoutMs != null ? Date.now() + timeoutMs : undefined, check)
|
|
571
|
+
await fg.verifyFrames()
|
|
572
|
+
return { result: await send(tabId, method, params || {}, timeoutMs, fg.pGuard, meta), attachSeq: meta.attachSeq || 0, controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
573
|
+
}
|
|
574
|
+
return { result: await send(tabId, method, params || {}, timeoutMs, check, meta), attachSeq: meta.attachSeq || 0, controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
575
|
+
},
|
|
576
|
+
|
|
577
|
+
async historyNav({ tabId, action, controlEpoch, noReattach = false, timeoutMs = 20000 }) {
|
|
578
|
+
if (!['back', 'forward', 'reload'].includes(action)) throw new Error(`不支持的历史导航动作: ${action}`)
|
|
579
|
+
const id = Number(tabId), deadline = Date.now() + timeoutMs
|
|
580
|
+
const globalEpoch = S.releaseAllEpoch
|
|
581
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
582
|
+
if (S.releasing.has(id)) throw new Error(RELEASED_MSG)
|
|
583
|
+
if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
|
|
584
|
+
if (noReattach && !S.attached.has(id)) throw new Error(RELEASED_MSG)
|
|
585
|
+
await within(ensure(id), timeLeft(deadline), '等待调试器超时')
|
|
586
|
+
const epoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0)
|
|
587
|
+
const seq = S.attachSeq.get(id)
|
|
588
|
+
const guard = () => {
|
|
589
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
590
|
+
if (!S.attached.has(id) || S.attachSeq.get(id) !== seq || S.releasing.has(id) ||
|
|
591
|
+
(S.controlEpoch.get(id) || 0) !== epoch || S.releaseAllEpoch !== globalEpoch) {
|
|
592
|
+
throw new Error(RELEASED_MSG)
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
guard()
|
|
596
|
+
if (action === 'reload') {
|
|
597
|
+
await send(id, 'Page.reload', {}, timeLeft(deadline), guard)
|
|
598
|
+
} else {
|
|
599
|
+
const h = await send(id, 'Page.getNavigationHistory', {}, timeLeft(deadline), guard)
|
|
600
|
+
guard()
|
|
601
|
+
const i = h.currentIndex + (action === 'back' ? -1 : 1)
|
|
602
|
+
if (i < 0 || i >= (h.entries || []).length) {
|
|
603
|
+
throw new Error(action === 'back' ? 'NAV_HISTORY_FIRST 已经是历史第一页,不能再后退' : 'NAV_HISTORY_LAST 已经是历史最后一页,不能再前进')
|
|
604
|
+
}
|
|
605
|
+
const entry = h.entries[i]
|
|
606
|
+
if (entry && isExtUrl(entry.url)) throw new Error('扩展页面(chrome-extension://)不能被自动化操作')
|
|
607
|
+
await send(id, 'Page.navigateToHistoryEntry', { entryId: entry.id }, timeLeft(deadline), guard)
|
|
608
|
+
}
|
|
609
|
+
return { ok: true, action, controlEpoch: epoch }
|
|
321
610
|
},
|
|
322
611
|
|
|
323
|
-
async nav({ tabId, url, wait =
|
|
612
|
+
async nav({ tabId, url, wait = 'load', timeoutMs = 30000, receipt = false }) {
|
|
613
|
+
const phase = waitPhase(wait)
|
|
324
614
|
const deadline = Date.now() + timeoutMs
|
|
325
|
-
const id =
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
clearTimeout(entry.timer)
|
|
335
|
-
entries.delete(entry)
|
|
336
|
-
if (!entries.size) S.loadWaiters.delete(id)
|
|
337
|
-
resolve(value)
|
|
338
|
-
} }
|
|
339
|
-
entries.add(entry)
|
|
340
|
-
S.loadWaiters.set(id, entries)
|
|
341
|
-
entry.timer = setTimeout(() => entry.finish(false), waitMs)
|
|
342
|
-
})
|
|
615
|
+
const id = Number(tabId), epoch = S.controlEpoch.get(id) || 0, globalEpoch = S.releaseAllEpoch
|
|
616
|
+
const guard = () => {
|
|
617
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
618
|
+
if (S.releasing.has(id) || (S.controlEpoch.get(id) || 0) !== epoch || globalEpoch !== S.releaseAllEpoch) throw new Error(RELEASED_MSG)
|
|
619
|
+
}
|
|
620
|
+
await within(ensure(id), timeoutMs, '等待调试器超时')
|
|
621
|
+
guard()
|
|
622
|
+
const before = receipt && await receiptState(id, deadline, guard)
|
|
623
|
+
const watcher = phase !== 'none' && watchLifecycle(id, phase, deadline)
|
|
343
624
|
let r, loaded = null
|
|
344
625
|
try {
|
|
345
|
-
r = await send(id, 'Page.navigate', { url }, timeLeft(deadline))
|
|
626
|
+
r = await send(id, 'Page.navigate', { url }, timeLeft(deadline), guard)
|
|
346
627
|
if (r.errorText) throw new Error(r.errorText)
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
628
|
+
if (watcher) {
|
|
629
|
+
watcher.bind(r)
|
|
630
|
+
if (r.frameId && !r.loaderId) {
|
|
631
|
+
if (phase !== 'idle') {
|
|
632
|
+
loaded = true
|
|
633
|
+
} else {
|
|
634
|
+
const idleStart = Date.now()
|
|
635
|
+
loaded = false
|
|
636
|
+
while (Date.now() < deadline) {
|
|
637
|
+
guard()
|
|
638
|
+
const busy = [...S.netPending.values()].some(n => n.tabId === id && !['EventSource', 'WebSocket'].includes(n.type))
|
|
639
|
+
if (!busy && Date.now() - Math.max(idleStart, S.netChanged.get(id) || 0) >= 500) {
|
|
640
|
+
loaded = true
|
|
641
|
+
break
|
|
642
|
+
}
|
|
643
|
+
await sleep(Math.min(25, Math.max(1, deadline - Date.now())))
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
} else {
|
|
647
|
+
loaded = await watcher.promise
|
|
648
|
+
}
|
|
649
|
+
if (loaded instanceof Error) throw loaded
|
|
650
|
+
}
|
|
651
|
+
} finally { if (watcher) watcher.finish(false) }
|
|
652
|
+
guard()
|
|
653
|
+
if (typeof chrome.tabs?.get !== 'function') {
|
|
654
|
+
const out = { url: url || '', title: '', frameId: r.frameId, waited: !!watcher, loaded }
|
|
655
|
+
if (receipt) {
|
|
656
|
+
out.receipt = {
|
|
657
|
+
beforeUrl: before?.url || '', beforeTitle: before?.title || '', url: url || '', title: '',
|
|
658
|
+
navigated: true, originChanged: false, protectedSite: false, pendingDialog: null,
|
|
659
|
+
liveUpdate: null, unverified: true, controlEpoch: S.controlEpoch.get(id) || 0,
|
|
660
|
+
navGeneration: S.mainNavGeneration.get(id) || 0,
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
return out
|
|
664
|
+
}
|
|
665
|
+
const landed = await pageAccess(id, { frames: false })
|
|
666
|
+
const reqOrigin = originOf(url)
|
|
667
|
+
const landedOrigin = originOf(landed.url)
|
|
668
|
+
const committedOrigin = originOf(landed.committedUrl || '')
|
|
669
|
+
const committedMismatch = Boolean(reqOrigin) && Boolean(committedOrigin) && committedOrigin !== reqOrigin
|
|
670
|
+
const unexpectedCross = landed.reason === 'protected' || (Boolean(reqOrigin) && (!landedOrigin || reqOrigin !== landedOrigin))
|
|
671
|
+
let after = unexpectedCross
|
|
672
|
+
? { url: landedOrigin, committedUrl: landed.committedUrl || '', committedSameOrigin: Boolean(landed.committedSameOrigin), title: '', live: [], secrets: [], ...(landed.reason && { reason: landed.reason }) }
|
|
673
|
+
: committedMismatch
|
|
674
|
+
? { url: landedOrigin || reqOrigin, committedUrl: landed.committedUrl, committedSameOrigin: false, title: '', live: [], secrets: [] }
|
|
675
|
+
: (receipt ? await receiptState(id, deadline, guard, [], reqOrigin || undefined, url || undefined) : landed)
|
|
676
|
+
guard()
|
|
677
|
+
const finalOrigin = originOf(after.url)
|
|
678
|
+
const finalCommittedOrigin = originOf(after.committedUrl || '')
|
|
679
|
+
const finalCommittedMismatch = Boolean(reqOrigin) && Boolean(finalCommittedOrigin) && finalCommittedOrigin !== reqOrigin
|
|
680
|
+
const finalCross = unexpectedCross || after.reason === 'protected' || after.reason === 'origin_changed' ||
|
|
681
|
+
(Boolean(reqOrigin) && (!finalOrigin || reqOrigin !== finalOrigin))
|
|
682
|
+
if (finalCross) {
|
|
683
|
+
after = { url: finalOrigin, committedUrl: after.committedUrl || '', committedSameOrigin: Boolean(after.committedSameOrigin), title: '', live: [], secrets: [], ...(after.reason && { reason: after.reason }) }
|
|
684
|
+
} else if (finalCommittedMismatch) {
|
|
685
|
+
after = { ...after, url: finalOrigin || reqOrigin, committedSameOrigin: false, title: '', live: [], secrets: [] }
|
|
686
|
+
}
|
|
687
|
+
const result = {
|
|
688
|
+
url: finalCross ? finalOrigin : finalCommittedMismatch ? (finalOrigin || reqOrigin) : (after.url || url),
|
|
689
|
+
title: finalCross || finalCommittedMismatch ? '' : after.title,
|
|
690
|
+
frameId: r.frameId, waited: !!watcher, loaded,
|
|
360
691
|
}
|
|
361
|
-
|
|
692
|
+
if (after.reason === 'protected') Object.assign(result, { url: after.url, protectedSite: true,
|
|
693
|
+
note: '跳到了受保护网站,标题和地址已隐藏;接下来在这个页面上读或操作都要用户先在弹窗里放行' })
|
|
694
|
+
if (receipt) {
|
|
695
|
+
const rct = receiptOf(id, before, after, undefined, [], !finalCross && !finalCommittedMismatch)
|
|
696
|
+
rct.navigated = true
|
|
697
|
+
rct.originChanged = finalCross || rct.protectedSite
|
|
698
|
+
if (finalCross || finalCommittedMismatch) {
|
|
699
|
+
rct.url = finalCross ? finalOrigin : (finalOrigin || reqOrigin)
|
|
700
|
+
rct.title = ''
|
|
701
|
+
rct.liveUpdate = null
|
|
702
|
+
if (rct.pendingDialog) {
|
|
703
|
+
rct.pendingDialog = (!after.committedSameOrigin || finalCommittedMismatch)
|
|
704
|
+
? null : { ...rct.pendingDialog, message: '' }
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
result.receipt = rct
|
|
708
|
+
result.url = rct.url
|
|
709
|
+
result.title = rct.title
|
|
710
|
+
}
|
|
711
|
+
return result
|
|
362
712
|
},
|
|
363
713
|
|
|
364
|
-
async click({ tabId, x, y, clickCount, button, chooser }) {
|
|
365
|
-
|
|
714
|
+
async click({ tabId, x, y, clickCount, button, chooser, noCursor, timeoutMs, expectedNavGen, expectedDocToken, expectedUrl, expectedUrlHash }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: optNavGen, releaseBinding, releaseNavGen } = {}) {
|
|
715
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
716
|
+
const navGen = Number.isInteger(optNavGen) ? optNavGen : (Number.isInteger(expectedNavGen) ? expectedNavGen : undefined)
|
|
717
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, navGen)
|
|
718
|
+
const binding = docBinding || ((expectedDocToken != null || expectedUrl || expectedUrlHash)
|
|
719
|
+
? { ...(expectedDocToken != null && { expectedDocToken }), ...(expectedUrl && { expectedUrl }), ...(expectedUrlHash && { expectedUrlHash }) }
|
|
720
|
+
: undefined)
|
|
721
|
+
const relGen = releaseNavGen ?? navGen ?? (S.mainNavGeneration.get(Number(tabId)) || 0)
|
|
722
|
+
return clickPoint(tabId, x, y, {
|
|
723
|
+
deadline: dl, check: fg.guard, pressCheck: fg.pGuard, verifyFrames: fg.verifyFrames, verifyFramesOnly: fg.verifyFramesOnly, beforePress, docBinding: binding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen, clickCount, button, chooser,
|
|
724
|
+
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} (${Math.round(x)}, ${Math.round(y)})` },
|
|
725
|
+
})
|
|
366
726
|
},
|
|
367
727
|
|
|
368
|
-
async clickEl({ tabId, selector, chooser, clickCount, button }, { deadline, check } = {}) {
|
|
728
|
+
async clickEl({ tabId, selector, chooser, clickCount, button, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress: extraBeforePress, docBinding, expectedNavGen: optNavGen, releaseBinding, releaseNavGen } = {}) {
|
|
729
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
730
|
+
const navGen = Number.isInteger(optNavGen) ? optNavGen : (Number.isInteger(expectedNavGen) ? expectedNavGen : undefined)
|
|
731
|
+
const relGen = releaseNavGen ?? navGen ?? (S.mainNavGeneration.get(Number(tabId)) || 0)
|
|
732
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, navGen)
|
|
733
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
734
|
+
verifyFrames = fg.verifyFrames; verifyFramesOnly = fg.verifyFramesOnly
|
|
369
735
|
const pt = await pointOf(tabId, `
|
|
370
736
|
const el = document.querySelector(${JSON.stringify(selector)});
|
|
371
737
|
if (!el) return null;
|
|
@@ -376,13 +742,96 @@ const OPS = {
|
|
|
376
742
|
if (inner) target = inner;
|
|
377
743
|
}
|
|
378
744
|
if (!__dsh_visible(target) && !target.getBoundingClientRect().width) return null;
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
745
|
+
const res = await __dsh_point(target);
|
|
746
|
+
if (!res) return null;
|
|
747
|
+
const covHit = res.occluded && typeof document.elementFromPoint === 'function' ? document.elementFromPoint(res.x, res.y) : null;
|
|
748
|
+
const insideAnc = (node, anc) => {
|
|
749
|
+
while (node) {
|
|
750
|
+
if (anc && typeof anc.contains === 'function' && anc.contains(node)) return true;
|
|
751
|
+
if (node === anc) return true;
|
|
752
|
+
node = node.getRootNode ? node.getRootNode().host : null;
|
|
753
|
+
}
|
|
754
|
+
return false;
|
|
755
|
+
};
|
|
756
|
+
const isAncestor = covHit && (covHit === document.body || covHit === document.documentElement || insideAnc(target, covHit));
|
|
757
|
+
window.__dshClickElTarget = {
|
|
758
|
+
el: typeof WeakRef === 'function' ? new WeakRef(target) : target,
|
|
759
|
+
cover: covHit && !isAncestor ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
760
|
+
};
|
|
761
|
+
return res;
|
|
762
|
+
`, dl, guard)
|
|
763
|
+
const beforePress = async () => {
|
|
764
|
+
if (extraBeforePress) await extraBeforePress()
|
|
765
|
+
const ok = await evaluate(tabId, `(() => {
|
|
766
|
+
const ref = window.__dshClickElTarget;
|
|
767
|
+
delete window.__dshClickElTarget;
|
|
768
|
+
if (!ref) return false;
|
|
769
|
+
const deref = (r) => (r && typeof r.deref === 'function' ? r.deref() : r);
|
|
770
|
+
const el = deref(ref.el);
|
|
771
|
+
const cov = deref(ref.cover);
|
|
772
|
+
if (!el || el.isConnected === false) return false;
|
|
773
|
+
const inside = (node, ancestor) => {
|
|
774
|
+
while (node) {
|
|
775
|
+
if (ancestor && typeof ancestor.contains === 'function' && ancestor.contains(node)) return true;
|
|
776
|
+
if (node === ancestor) return true;
|
|
777
|
+
node = node.getRootNode ? node.getRootNode().host : null;
|
|
778
|
+
}
|
|
779
|
+
return false;
|
|
780
|
+
};
|
|
781
|
+
if (typeof document.elementFromPoint === 'function') {
|
|
782
|
+
const px = ${Math.round(pt.x)}, py = ${Math.round(pt.y)};
|
|
783
|
+
const hit = document.elementFromPoint(px, py);
|
|
784
|
+
if (!hit) return false;
|
|
785
|
+
const visibleInClip = (node) => {
|
|
786
|
+
let anc = node.parentElement || (node.getRootNode && node.getRootNode().host) || null;
|
|
787
|
+
const clipRe = /hidden|clip|auto|scroll/;
|
|
788
|
+
while (anc && anc !== document.body && anc !== document.documentElement) {
|
|
789
|
+
const as = typeof getComputedStyle === 'function' ? getComputedStyle(anc) : null;
|
|
790
|
+
const cx = clipRe.test(as?.overflowX || as?.overflow || '');
|
|
791
|
+
const cy = clipRe.test(as?.overflowY || as?.overflow || '');
|
|
792
|
+
if ((cx || cy) && typeof anc.getBoundingClientRect === 'function') {
|
|
793
|
+
const ar = anc.getBoundingClientRect();
|
|
794
|
+
if (cx && (ar.width <= 0 || px < ar.left || px > ar.right)) return false;
|
|
795
|
+
if (cy && (ar.height <= 0 || py < ar.top || py > ar.bottom)) return false;
|
|
796
|
+
}
|
|
797
|
+
anc = anc.parentElement || (anc.getRootNode && anc.getRootNode().host) || null;
|
|
798
|
+
}
|
|
799
|
+
return true;
|
|
800
|
+
};
|
|
801
|
+
const clickableAnc = (node) => {
|
|
802
|
+
if (!node || node === document.body || node === document.documentElement) return false;
|
|
803
|
+
const tag = node.tagName;
|
|
804
|
+
if (tag === 'A' || tag === 'BUTTON' || tag === 'LABEL' || tag === 'SUMMARY') return true;
|
|
805
|
+
const role = typeof node.getAttribute === 'function' ? (node.getAttribute('role') || '') : '';
|
|
806
|
+
if (/^(button|link|tab|menuitem|option|checkbox|radio|switch)$/i.test(role)) return true;
|
|
807
|
+
if (typeof node.onclick === 'function' || (typeof node.getAttribute === 'function' && (node.getAttribute('onclick') || node.getAttribute('tabindex') != null))) return true;
|
|
808
|
+
const hs = typeof getComputedStyle === 'function' ? getComputedStyle(node) : null;
|
|
809
|
+
return hs?.cursor === 'pointer';
|
|
810
|
+
};
|
|
811
|
+
const ancestorOk = inside(el, hit) && clickableAnc(hit) && visibleInClip(el) &&
|
|
812
|
+
typeof getComputedStyle === 'function' && getComputedStyle(el)?.pointerEvents === 'none';
|
|
813
|
+
const onTarget = inside(hit, el) || ancestorOk;
|
|
814
|
+
const onSameCover = Boolean(cov) && cov !== document.body && cov !== document.documentElement && !inside(el, cov) && inside(hit, cov);
|
|
815
|
+
if (!onTarget && !onSameCover) return false;
|
|
816
|
+
}
|
|
817
|
+
return true;
|
|
818
|
+
})()`, false, dl && timeLeft(dl), guard)
|
|
819
|
+
if (!ok) throw new Error('目标元素在点击前已变化或被容器裁切遮挡,已中止点击')
|
|
820
|
+
}
|
|
821
|
+
const hit = await clickPoint(tabId, pt.x, pt.y, {
|
|
822
|
+
deadline: dl, check: guard, pressCheck: pGuard, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen, clickCount, button, chooser,
|
|
823
|
+
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` },
|
|
824
|
+
})
|
|
382
825
|
return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
|
|
383
826
|
},
|
|
384
827
|
|
|
385
|
-
async clickText({ tabId, text, exact = true, index = 0, chooser, clickCount, button }) {
|
|
828
|
+
async clickText({ tabId, text, exact = true, index = 0, chooser, clickCount, button, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress: extraBeforePress, docBinding, expectedNavGen: optNavGen, releaseBinding, releaseNavGen } = {}) {
|
|
829
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
830
|
+
const navGen = Number.isInteger(optNavGen) ? optNavGen : (Number.isInteger(expectedNavGen) ? expectedNavGen : undefined)
|
|
831
|
+
const relGen = releaseNavGen ?? navGen ?? (S.mainNavGeneration.get(Number(tabId)) || 0)
|
|
832
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, navGen)
|
|
833
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
834
|
+
verifyFrames = fg.verifyFrames; verifyFramesOnly = fg.verifyFramesOnly
|
|
386
835
|
const pt = await pointOf(tabId, `
|
|
387
836
|
const want = __dsh_norm(${JSON.stringify(text)});
|
|
388
837
|
const SEL = 'a,button,input,textarea,select,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[contenteditable=true],li,td,th,h1,h2,h3,h4,span,div,p';
|
|
@@ -394,8 +843,8 @@ const OPS = {
|
|
|
394
843
|
hit.sort((a, b) => { const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return ra.width * ra.height - rb.width * rb.height; });
|
|
395
844
|
const el = hit[Math.min(${Number(index) || 0}, hit.length - 1)];
|
|
396
845
|
// 元素框常常比可见按钮大得多(<a> 里塞满空白),点框中心会落在按钮外面。
|
|
397
|
-
//
|
|
398
|
-
const
|
|
846
|
+
// 先找承载这段文字的文本节点,把对应元素滚进视口后再用 Range 拿它的精确视口坐标。
|
|
847
|
+
const findTextNode = (root, needle) => {
|
|
399
848
|
const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
400
849
|
let n;
|
|
401
850
|
while ((n = w.nextNode())) {
|
|
@@ -405,51 +854,288 @@ const OPS = {
|
|
|
405
854
|
const rg = document.createRange();
|
|
406
855
|
rg.selectNodeContents(n);
|
|
407
856
|
const rc = rg.getBoundingClientRect();
|
|
408
|
-
if (rc.width > 0 && rc.height > 0) return
|
|
857
|
+
if (rc.width > 0 && rc.height > 0) return n;
|
|
409
858
|
}
|
|
410
859
|
}
|
|
411
860
|
return null;
|
|
412
861
|
};
|
|
413
|
-
const
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
862
|
+
const textNode = findTextNode(el, want);
|
|
863
|
+
await __dsh_scroll_wait((textNode && textNode.parentElement) || el);
|
|
864
|
+
if (el.isConnected === false) return null;
|
|
865
|
+
const pr = el.getBoundingClientRect();
|
|
866
|
+
if (pr.width < 1 || pr.height < 1) return null;
|
|
867
|
+
// 虚拟列表滚后可能复用原 DOM / 文本节点并换掉文字,必须按原始 exact 条件重新校验
|
|
868
|
+
const afterLabel = label(el);
|
|
869
|
+
const labelOk = afterLabel === want || (${exact ? 'false' : 'true'} && afterLabel.includes(want));
|
|
870
|
+
if (!labelOk) return null;
|
|
871
|
+
if (textNode) {
|
|
872
|
+
const nodeText = __dsh_norm(textNode.nodeValue || '');
|
|
873
|
+
const nodeStillMatches = textNode.isConnected !== false &&
|
|
874
|
+
(typeof el.contains !== 'function' || el.contains(textNode)) &&
|
|
875
|
+
(nodeText === want || nodeText.includes(want));
|
|
876
|
+
const liveNode = nodeStillMatches ? textNode : findTextNode(el, want);
|
|
877
|
+
if (!liveNode) return null;
|
|
878
|
+
const rg = document.createRange();
|
|
879
|
+
rg.selectNodeContents(liveNode);
|
|
880
|
+
const tr = rg.getBoundingClientRect();
|
|
881
|
+
if (tr.width < 1 || tr.height < 1) return null;
|
|
882
|
+
const tl = tr.left != null ? tr.left : tr.x, tt = tr.top != null ? tr.top : tr.y;
|
|
883
|
+
const cx = Math.round(tl + tr.width / 2), cy = Math.round(tt + tr.height / 2);
|
|
884
|
+
const pl = pr.left != null ? pr.left : pr.x, pt0 = pr.top != null ? pr.top : pr.y;
|
|
885
|
+
const cov = __dsh_cover(el, cx, cy);
|
|
886
|
+
const covHit = cov.occluded && typeof document.elementFromPoint === 'function' ? document.elementFromPoint(cx, cy) : null;
|
|
887
|
+
const insideAnc = (node, anc) => {
|
|
888
|
+
while (node) {
|
|
889
|
+
if (anc && typeof anc.contains === 'function' && anc.contains(node)) return true;
|
|
890
|
+
if (node === anc) return true;
|
|
891
|
+
node = node.getRootNode ? node.getRootNode().host : null;
|
|
892
|
+
}
|
|
893
|
+
return false;
|
|
894
|
+
};
|
|
895
|
+
const isAnc = covHit && (covHit === document.body || covHit === document.documentElement || insideAnc(el, covHit));
|
|
896
|
+
window.__dshClickTextTarget = {
|
|
897
|
+
el: typeof WeakRef === 'function' ? new WeakRef(el) : el,
|
|
898
|
+
textNode: typeof WeakRef === 'function' ? new WeakRef(liveNode) : liveNode,
|
|
899
|
+
cover: covHit && !isAnc ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
900
|
+
};
|
|
901
|
+
return { ...cov, x: cx, y: cy,
|
|
417
902
|
text: (el.innerText || '').trim().slice(0, 60), tag: el.tagName.toLowerCase(),
|
|
418
|
-
rect: [Math.round(
|
|
419
|
-
textRect: [Math.round(
|
|
903
|
+
rect: [Math.round(pl), Math.round(pt0), Math.round(pr.width), Math.round(pr.height)],
|
|
904
|
+
textRect: [Math.round(tl), Math.round(tt), Math.round(tr.width), Math.round(tr.height)] };
|
|
420
905
|
}
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
906
|
+
const ex = pr.left + pr.width / 2, ey = pr.top + pr.height / 2;
|
|
907
|
+
const cov = __dsh_cover(el, ex, ey);
|
|
908
|
+
const covHit = cov.occluded && typeof document.elementFromPoint === 'function' ? document.elementFromPoint(ex, ey) : null;
|
|
909
|
+
const insideAnc2 = (node, anc) => {
|
|
910
|
+
while (node) {
|
|
911
|
+
if (anc && typeof anc.contains === 'function' && anc.contains(node)) return true;
|
|
912
|
+
if (node === anc) return true;
|
|
913
|
+
node = node.getRootNode ? node.getRootNode().host : null;
|
|
914
|
+
}
|
|
915
|
+
return false;
|
|
916
|
+
};
|
|
917
|
+
const isAnc2 = covHit && (covHit === document.body || covHit === document.documentElement || insideAnc2(el, covHit));
|
|
918
|
+
window.__dshClickTextTarget = {
|
|
919
|
+
el: typeof WeakRef === 'function' ? new WeakRef(el) : el,
|
|
920
|
+
textNode: null,
|
|
921
|
+
cover: covHit && !isAnc2 ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
922
|
+
};
|
|
923
|
+
return { ...cov, x: ex, y: ey, tag: el.tagName.toLowerCase(),
|
|
924
|
+
text: __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') ||
|
|
925
|
+
el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) };
|
|
926
|
+
`, dl, guard)
|
|
927
|
+
// mouseMoved 后、mousePressed 前始终核对坐标命中元素,防止遮挡消失或悬停重排后误点同行/邻行同名按钮
|
|
928
|
+
const beforePress = async () => {
|
|
929
|
+
if (extraBeforePress) await extraBeforePress()
|
|
930
|
+
const ok = await evaluate(tabId, `(() => {
|
|
931
|
+
const ref = window.__dshClickTextTarget;
|
|
932
|
+
delete window.__dshClickTextTarget;
|
|
933
|
+
const want = ${JSON.stringify(String(text || '').replace(/\s+/g, ' ').trim())};
|
|
934
|
+
const exact = ${Boolean(exact)};
|
|
935
|
+
const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
936
|
+
const label = (el) => norm(el && (el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') ||
|
|
937
|
+
(typeof el.getAttribute === 'function' ? (el.getAttribute('aria-label') || el.getAttribute('placeholder') || '') : '')));
|
|
938
|
+
const match = (s) => s === want || (!exact && s.includes(want));
|
|
939
|
+
const inside = (node, ancestor) => {
|
|
940
|
+
while (node) {
|
|
941
|
+
if (ancestor && typeof ancestor.contains === 'function' && ancestor.contains(node)) return true;
|
|
942
|
+
if (node === ancestor) return true;
|
|
943
|
+
node = node.getRootNode ? node.getRootNode().host : null;
|
|
944
|
+
}
|
|
945
|
+
return false;
|
|
946
|
+
};
|
|
947
|
+
const deref = (r) => (r && typeof r.deref === 'function' ? r.deref() : r);
|
|
948
|
+
if (!ref) return false;
|
|
949
|
+
const el = deref(ref.el);
|
|
950
|
+
const cov = deref(ref.cover);
|
|
951
|
+
if (!el || el.isConnected === false) return false;
|
|
952
|
+
if (!match(label(el))) return false;
|
|
953
|
+
if (ref.textNode) {
|
|
954
|
+
const tn = deref(ref.textNode);
|
|
955
|
+
const nt = norm((tn && tn.nodeValue) || '');
|
|
956
|
+
if (!tn || tn.isConnected === false || (typeof el.contains === 'function' && !el.contains(tn) && tn.parentElement !== el) || !(nt === want || nt.includes(want))) {
|
|
957
|
+
return false;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
if (typeof document.elementFromPoint === 'function') {
|
|
961
|
+
const px = ${Math.round(pt.x)}, py = ${Math.round(pt.y)};
|
|
962
|
+
const hit = document.elementFromPoint(px, py);
|
|
963
|
+
if (!hit) return false;
|
|
964
|
+
const visibleInClip = (node) => {
|
|
965
|
+
let anc = node.parentElement || (node.getRootNode && node.getRootNode().host) || null;
|
|
966
|
+
const clipRe = /hidden|clip|auto|scroll/;
|
|
967
|
+
while (anc && anc !== document.body && anc !== document.documentElement) {
|
|
968
|
+
const as = typeof getComputedStyle === 'function' ? getComputedStyle(anc) : null;
|
|
969
|
+
const cx = clipRe.test(as?.overflowX || as?.overflow || '');
|
|
970
|
+
const cy = clipRe.test(as?.overflowY || as?.overflow || '');
|
|
971
|
+
if ((cx || cy) && typeof anc.getBoundingClientRect === 'function') {
|
|
972
|
+
const ar = anc.getBoundingClientRect();
|
|
973
|
+
if (cx && (ar.width <= 0 || px < ar.left || px > ar.right)) return false;
|
|
974
|
+
if (cy && (ar.height <= 0 || py < ar.top || py > ar.bottom)) return false;
|
|
975
|
+
}
|
|
976
|
+
anc = anc.parentElement || (anc.getRootNode && anc.getRootNode().host) || null;
|
|
977
|
+
}
|
|
978
|
+
return true;
|
|
979
|
+
};
|
|
980
|
+
const clickableAnc = (node) => {
|
|
981
|
+
if (!node || node === document.body || node === document.documentElement) return false;
|
|
982
|
+
const tag = node.tagName;
|
|
983
|
+
if (tag === 'A' || tag === 'BUTTON' || tag === 'LABEL' || tag === 'SUMMARY') return true;
|
|
984
|
+
const role = typeof node.getAttribute === 'function' ? (node.getAttribute('role') || '') : '';
|
|
985
|
+
if (/^(button|link|tab|menuitem|option|checkbox|radio|switch)$/i.test(role)) return true;
|
|
986
|
+
if (typeof node.onclick === 'function' || (typeof node.getAttribute === 'function' && (node.getAttribute('onclick') || node.getAttribute('tabindex') != null))) return true;
|
|
987
|
+
const hs = typeof getComputedStyle === 'function' ? getComputedStyle(node) : null;
|
|
988
|
+
return hs?.cursor === 'pointer';
|
|
989
|
+
};
|
|
990
|
+
const ancestorOk = inside(el, hit) && clickableAnc(hit) && visibleInClip(el) &&
|
|
991
|
+
typeof getComputedStyle === 'function' && getComputedStyle(el)?.pointerEvents === 'none';
|
|
992
|
+
const onTarget = inside(hit, el) || ancestorOk;
|
|
993
|
+
const onSameCover = Boolean(cov) && cov !== document.body && cov !== document.documentElement && !inside(el, cov) && inside(hit, cov);
|
|
994
|
+
if (!onTarget && !onSameCover) return false;
|
|
995
|
+
}
|
|
996
|
+
return true;
|
|
997
|
+
})()`, false, dl && timeLeft(dl), guard)
|
|
998
|
+
if (!ok) throw new Error('目标文字在点击前已变化,已中止点击')
|
|
999
|
+
}
|
|
1000
|
+
const hit = await clickPoint(tabId, pt.x, pt.y, {
|
|
1001
|
+
deadline: dl, check: guard, pressCheck: pGuard, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen, clickCount, button, chooser,
|
|
1002
|
+
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` },
|
|
1003
|
+
})
|
|
424
1004
|
return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
|
|
425
1005
|
},
|
|
426
1006
|
|
|
427
|
-
async type({ tabId, text, selector }) {
|
|
428
|
-
|
|
429
|
-
|
|
1007
|
+
async type({ tabId, text, selector, clear = false, submit = false, chooser, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress, docBinding, docGuardJs = '', expectedNavGen: optNavGen, releaseBinding, releaseNavGen, onSensitive } = {}) {
|
|
1008
|
+
const id = Number(tabId)
|
|
1009
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
1010
|
+
const navGen = Number.isInteger(optNavGen) ? optNavGen : (Number.isInteger(expectedNavGen) ? expectedNavGen : undefined)
|
|
1011
|
+
const relGen = releaseNavGen ?? navGen ?? (S.mainNavGeneration.get(id) || 0)
|
|
1012
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, navGen)
|
|
1013
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
1014
|
+
verifyFrames = fg.verifyFrames; verifyFramesOnly = fg.verifyFramesOnly
|
|
1015
|
+
const runBefore = async () => { if (beforePress) await beforePress(); await verifyFrames() }
|
|
1016
|
+
const budget = () => (dl !== undefined ? timeLeft(dl) : undefined)
|
|
1017
|
+
const cursorDeadline = () => (dl !== undefined ? dl : Date.now() + 1500)
|
|
1018
|
+
if (selector) await getOps().clickEl({ tabId, selector, noCursor, timeoutMs, expectedNavGen: navGen }, { deadline: dl, check: guard, pressCheck: pGuard, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen })
|
|
1019
|
+
guard()
|
|
1020
|
+
await (dl !== undefined ? within(ensure(tabId), budget(), '等待调试器超时') : ensure(tabId))
|
|
1021
|
+
guard()
|
|
430
1022
|
// 名牌写上在输什么。只有确认焦点落在普通(非密码)输入框里才亮原文:焦点在 shadow DOM / 同源 iframe 里
|
|
431
|
-
// 就往里找真正的焦点元素;找不到(跨域 iframe、关闭的 shadow root
|
|
432
|
-
const sensitive =
|
|
433
|
-
|
|
1023
|
+
// 就往里找真正的焦点元素;找不到(跨域 iframe、关闭的 shadow root……)或者是密码/验证码样式的框,一律打码
|
|
1024
|
+
const sensitive = sensitiveValue(text)
|
|
1025
|
+
if (onSensitive && text) {
|
|
1026
|
+
const masked = sensitive || await evaluate(tabId, `(() => {
|
|
1027
|
+
let el = document.activeElement;
|
|
1028
|
+
while (el) {
|
|
1029
|
+
const next = el.shadowRoot?.activeElement || el.contentDocument?.activeElement;
|
|
1030
|
+
if (!next) break;
|
|
1031
|
+
el = next;
|
|
1032
|
+
}
|
|
1033
|
+
if (!el || (!['INPUT', 'TEXTAREA'].includes(el.tagName) && !el.isContentEditable)) return true;
|
|
1034
|
+
return (${isSensitiveField})(el, el.ownerDocument.defaultView.getComputedStyle(el), true)
|
|
1035
|
+
|| el.getAttribute('inputmode') === 'numeric';
|
|
1036
|
+
})()`, false, budget(), guard).catch(() => true)
|
|
1037
|
+
if (masked) onSensitive(text)
|
|
1038
|
+
guard()
|
|
1039
|
+
}
|
|
434
1040
|
const shown = sensitive ? 'null' : JSON.stringify(text.length > 24 ? text.slice(0, 24) + '…' : text)
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
1041
|
+
if (!noCursor && S.showCursor) {
|
|
1042
|
+
if (!S.cursorReady.has(id)) {
|
|
1043
|
+
const cdl = cursorDeadline()
|
|
1044
|
+
const box = await evaluate(tabId, `(() => {
|
|
1045
|
+
let a = document.activeElement;
|
|
1046
|
+
for (let i = 0; a && i < 32; i++) {
|
|
1047
|
+
if (a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; continue; }
|
|
1048
|
+
break;
|
|
1049
|
+
}
|
|
1050
|
+
if (!a || typeof a.getBoundingClientRect !== 'function') return null;
|
|
1051
|
+
const r = a.getBoundingClientRect();
|
|
1052
|
+
if (r.width < 1 || r.height < 1) return null;
|
|
1053
|
+
return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
|
|
1054
|
+
})()`, false, timeLeft(cdl)).catch((e) => {
|
|
1055
|
+
if (dl !== undefined && Date.now() >= dl) throw e
|
|
1056
|
+
return null
|
|
1057
|
+
})
|
|
1058
|
+
guard()
|
|
1059
|
+
if (box) {
|
|
1060
|
+
await cursorMove(tabId, box.x, box.y, { duration: 0, agentMs: 1500, deadline: cursorDeadline() }).catch((e) => {
|
|
1061
|
+
if (dl !== undefined) throw e
|
|
1062
|
+
return null
|
|
1063
|
+
})
|
|
1064
|
+
} else if (S.cursorPos.has(id)) {
|
|
1065
|
+
await injectCursor(tabId, cursorDeadline()).catch((e) => {
|
|
1066
|
+
if (dl !== undefined) throw e
|
|
1067
|
+
return false
|
|
1068
|
+
})
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
guard()
|
|
1072
|
+
if (S.cursorReady.has(id)) {
|
|
1073
|
+
await cursorFx(tabId, `(() => {
|
|
1074
|
+
let a = document.activeElement;
|
|
1075
|
+
for (let i = 0; a && i < 32; i++) {
|
|
1076
|
+
if (a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; continue; }
|
|
1077
|
+
if (a.tagName === 'IFRAME' || a.tagName === 'FRAME') { let d = null; try { d = a.contentDocument; } catch {} a = d && d.activeElement; continue; }
|
|
1078
|
+
break;
|
|
1079
|
+
}
|
|
1080
|
+
let plain = false;
|
|
1081
|
+
try {
|
|
1082
|
+
const st = (a.ownerDocument.defaultView || window).getComputedStyle(a);
|
|
1083
|
+
const sec = st.webkitTextSecurity || 'none';
|
|
1084
|
+
const ga = (k) => (typeof a.getAttribute === 'function' ? a.getAttribute(k) || '' : '');
|
|
1085
|
+
const fields = [a.name, a.id, a.autocomplete, ga('name'), ga('id'), ga('autocomplete'), ga('aria-label'), ga('placeholder'), ga('title')].filter(Boolean).join(' ');
|
|
1086
|
+
const masked = typeof a.getAttribute === 'function' && (${isSensitiveField})(a, st, true);
|
|
1087
|
+
plain = !masked && ((a.tagName === 'INPUT' && a.type !== 'password') || a.tagName === 'TEXTAREA' || a.isContentEditable) && sec === 'none' &&
|
|
1088
|
+
a.type !== 'tel' && !/one-time-code|current-password|new-password|cc-number|cc-csc/i.test(fields) &&
|
|
1089
|
+
a.inputMode !== 'numeric' && !/^numeric$/i.test(ga('inputmode')) &&
|
|
1090
|
+
!/code|verif|2fa|mfa|pin|otp|cvv|cvc|card|secret|token|pwd|pass|api[_-]?key|验证码|校验码|动态码|安全码|口令|密码|密钥|银行卡|卡号|令牌|парол|код\s*(?:подтвержд|доступа|безопасн|проверк)|смс[- ]?код|пин[- ]?код|секрет|токен|номер\s*карт/i.test(fields);
|
|
1091
|
+
} catch {}
|
|
1092
|
+
window.__dshCursor.beginAgent && window.__dshCursor.beginAgent(1500);
|
|
1093
|
+
window.__dshCursor.label(${JSON.stringify(labels[S.UI_LANG].type + ' ')} + (plain && ${!sensitive} ? ${shown} : '••••••'));
|
|
1094
|
+
return 1;
|
|
1095
|
+
})()`, cursorDeadline()).catch((e) => {
|
|
1096
|
+
if (dl !== undefined) throw e
|
|
1097
|
+
return undefined
|
|
1098
|
+
})
|
|
1099
|
+
if (S.cursorReady.has(id)) S.pageAgentUntil.set(id, Date.now() + 1500)
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
guard()
|
|
1103
|
+
if (clear) {
|
|
1104
|
+
const cleared = await evaluate(tabId, `(() => {
|
|
1105
|
+
${docGuardJs}
|
|
1106
|
+
let el = document.activeElement;
|
|
1107
|
+
while (el) {
|
|
1108
|
+
const next = el.shadowRoot?.activeElement || el.contentDocument?.activeElement;
|
|
1109
|
+
if (!next) break;
|
|
1110
|
+
el = next;
|
|
1111
|
+
}
|
|
1112
|
+
if (!el || el.disabled || el.readOnly) return { ok: false };
|
|
1113
|
+
if (el.isContentEditable) {
|
|
1114
|
+
const range = el.ownerDocument.createRange();
|
|
1115
|
+
range.selectNodeContents(el);
|
|
1116
|
+
const sel = el.ownerDocument.getSelection();
|
|
1117
|
+
sel.removeAllRanges(); sel.addRange(range);
|
|
1118
|
+
} else if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && /^(text|search|email|tel|password|url|number)$/.test(el.type))) el.select();
|
|
1119
|
+
else return { ok: false };
|
|
1120
|
+
return { ok: true };
|
|
1121
|
+
})()`, false, budget(), guard)
|
|
1122
|
+
if (cleared?.navigated) throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
|
|
1123
|
+
if (!cleared?.ok) throw new Error('当前焦点不是可编辑输入框')
|
|
1124
|
+
await runBefore()
|
|
1125
|
+
await pressKey(tabId, 'Backspace', { deadline: dl, check: pGuard, verifyFramesOnly, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen })
|
|
1126
|
+
}
|
|
1127
|
+
if (text.length) {
|
|
1128
|
+
await runBefore()
|
|
1129
|
+
await send(tabId, 'Input.insertText', { text }, budget(), pGuard, docBinding ? { docBinding } : undefined)
|
|
1130
|
+
}
|
|
1131
|
+
if (submit) {
|
|
1132
|
+
const result = await withChooser(tabId, chooser, async () => {
|
|
1133
|
+
await runBefore()
|
|
1134
|
+
await pressKey(tabId, 'Enter', { deadline: dl, check: pGuard, verifyFramesOnly, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen })
|
|
1135
|
+
return { submitted: true }
|
|
1136
|
+
})
|
|
1137
|
+
return { typed: text.length, selector: selector || null, ...result }
|
|
1138
|
+
}
|
|
453
1139
|
return { typed: text.length, selector: selector || null }
|
|
454
1140
|
},
|
|
455
1141
|
|
|
@@ -479,19 +1165,28 @@ const OPS = {
|
|
|
479
1165
|
return { selector, name, value }
|
|
480
1166
|
},
|
|
481
1167
|
|
|
482
|
-
async info({ tabId }) {
|
|
483
|
-
const
|
|
1168
|
+
async info({ tabId, noReattach = false, controlEpoch }) {
|
|
1169
|
+
const id = Number(tabId)
|
|
1170
|
+
if (Number.isInteger(controlEpoch) && (S.paused || S.releasing.has(id) || (S.controlEpoch.get(id) || 0) !== controlEpoch)) {
|
|
1171
|
+
throw new Error(RELEASED_MSG)
|
|
1172
|
+
}
|
|
1173
|
+
if (noReattach && (S.paused || S.releasing.has(id) || !S.attached.has(id))) {
|
|
1174
|
+
throw new Error(RELEASED_MSG)
|
|
1175
|
+
}
|
|
1176
|
+
const t = await chrome.tabs.get(id)
|
|
484
1177
|
let viewport = null
|
|
485
1178
|
try {
|
|
486
|
-
await ensure(tabId)
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
1179
|
+
if (!noReattach) await ensure(tabId)
|
|
1180
|
+
if (S.attached.has(id)) {
|
|
1181
|
+
const m = await send(tabId, 'Page.getLayoutMetrics')
|
|
1182
|
+
const v = m.cssVisualViewport
|
|
1183
|
+
viewport = { w: Math.round(v.clientWidth), h: Math.round(v.clientHeight), scrollY: Math.round(v.pageY) }
|
|
1184
|
+
}
|
|
490
1185
|
} catch {}
|
|
491
1186
|
return {
|
|
492
|
-
tabId:
|
|
493
|
-
windowId: t.windowId, active: t.active, attached: S.attached.has(
|
|
494
|
-
viewport, pendingDialog: S.dialogs.get(
|
|
1187
|
+
tabId: id, url: t.url, title: t.title, status: t.status,
|
|
1188
|
+
windowId: t.windowId, active: t.active, attached: S.attached.has(id),
|
|
1189
|
+
viewport, pendingDialog: S.dialogs.get(id) || null,
|
|
495
1190
|
}
|
|
496
1191
|
},
|
|
497
1192
|
|
|
@@ -516,35 +1211,165 @@ const OPS = {
|
|
|
516
1211
|
|
|
517
1212
|
// ── 输入类 ───────────────────────────────────────────────────────────────
|
|
518
1213
|
|
|
519
|
-
async hover({ tabId, x, y, selector }) {
|
|
1214
|
+
async hover({ tabId, x, y, selector, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress, docBinding } = {}) {
|
|
1215
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
1216
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, expectedNavGen)
|
|
1217
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
1218
|
+
verifyFrames = fg.verifyFrames
|
|
520
1219
|
let px = Number(x) || 0, py = Number(y) || 0, target = null
|
|
521
1220
|
if (selector) {
|
|
522
|
-
const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el)
|
|
1221
|
+
const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el);`, dl, guard)
|
|
523
1222
|
px = pt.x; py = pt.y; target = pt
|
|
524
1223
|
}
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
1224
|
+
guard()
|
|
1225
|
+
if (!noCursor && S.showCursor) {
|
|
1226
|
+
await moveForAction(tabId, px, py, {
|
|
1227
|
+
check: guard,
|
|
1228
|
+
label: `${labels[S.UI_LANG].hover} ${target ? target.text || target.tag : `(${Math.round(px)}, ${Math.round(py)})`}`,
|
|
1229
|
+
deadline: dl,
|
|
1230
|
+
agentMs: 1500,
|
|
1231
|
+
})
|
|
528
1232
|
}
|
|
529
|
-
|
|
1233
|
+
if (beforePress) await beforePress()
|
|
1234
|
+
await verifyFrames()
|
|
1235
|
+
pGuard()
|
|
1236
|
+
await send(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: Math.round(px), y: Math.round(py), buttons: 0 }, dl && timeLeft(dl), pGuard, docBinding ? { docBinding } : undefined)
|
|
530
1237
|
return { x: Math.round(px), y: Math.round(py), target }
|
|
531
1238
|
},
|
|
532
1239
|
|
|
533
|
-
async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0 }) {
|
|
534
|
-
const
|
|
535
|
-
|
|
1240
|
+
async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress } = {}) {
|
|
1241
|
+
const id = Number(tabId)
|
|
1242
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
1243
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, expectedNavGen)
|
|
1244
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
1245
|
+
verifyFrames = fg.verifyFrames
|
|
1246
|
+
const budget = () => (dl !== undefined ? timeLeft(dl) : undefined)
|
|
1247
|
+
const cursorDeadline = () => (dl !== undefined ? dl : Date.now() + 1500)
|
|
1248
|
+
guard()
|
|
1249
|
+
const snapScrollJs = `(() => {
|
|
1250
|
+
const list = [];
|
|
1251
|
+
const wins = [];
|
|
1252
|
+
let unobservable = false;
|
|
1253
|
+
const trackAncestors = (start) => {
|
|
1254
|
+
let cur = start;
|
|
1255
|
+
while (cur && cur.nodeType === 1) {
|
|
1256
|
+
if (cur.scrollHeight > cur.clientHeight + 1 || cur.scrollWidth > cur.clientWidth + 1) {
|
|
1257
|
+
list.push([typeof WeakRef === 'function' ? new WeakRef(cur) : cur, cur.scrollLeft || 0, cur.scrollTop || 0]);
|
|
1258
|
+
}
|
|
1259
|
+
cur = cur.parentElement || (cur.getRootNode && cur.getRootNode().host) || null;
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
const hasComplexTransform = (node, view) => {
|
|
1263
|
+
for (let n = node; n && n.nodeType === 1; n = n.assignedSlot || n.parentElement || (n.getRootNode && n.getRootNode().host)) {
|
|
1264
|
+
const s = view && typeof view.getComputedStyle === 'function' ? view.getComputedStyle(n) : null;
|
|
1265
|
+
if (!s) continue;
|
|
1266
|
+
if ((s.perspective && s.perspective !== 'none') || (s.rotate && s.rotate !== 'none' && s.rotate !== '0deg')) return true;
|
|
1267
|
+
if (s.scale && s.scale !== 'none') {
|
|
1268
|
+
const parts = String(s.scale).trim().split(/\\s+/).map((v) => v.endsWith('%') ? parseFloat(v) / 100 : Number(v));
|
|
1269
|
+
if (!parts.length || parts.some((n) => !Number.isFinite(n) || n <= 0) || (parts.length >= 3 && parts[2] !== 1)) return true;
|
|
1270
|
+
}
|
|
1271
|
+
if (s.transform && s.transform !== 'none') {
|
|
1272
|
+
if (typeof view.DOMMatrixReadOnly === 'function') {
|
|
1273
|
+
const m = new view.DOMMatrixReadOnly(s.transform);
|
|
1274
|
+
if (!m.is2D || m.b || m.c || m.a <= 0 || m.d <= 0) return true;
|
|
1275
|
+
} else {
|
|
1276
|
+
const m = /^matrix\\(\\s*([+-]?[\\d.eE]+)\\s*,\\s*([+-]?[\\d.eE]+)\\s*,\\s*([+-]?[\\d.eE]+)\\s*,\\s*([+-]?[\\d.eE]+)\\s*,/.exec(s.transform);
|
|
1277
|
+
if (!m || Number(m[2]) !== 0 || Number(m[3]) !== 0 || !(Number(m[1]) > 0) || !(Number(m[4]) > 0)) return true;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
return false;
|
|
1282
|
+
};
|
|
1283
|
+
let doc = document, px = ${Math.round(x)}, py = ${Math.round(y)};
|
|
1284
|
+
for (let depth = 0; depth < 6; depth++) {
|
|
1285
|
+
const hit = typeof doc?.elementFromPoint === 'function' ? doc.elementFromPoint(px, py) : null;
|
|
1286
|
+
if (!hit) break;
|
|
1287
|
+
trackAncestors(hit);
|
|
1288
|
+
if (hit.tagName !== 'IFRAME' && hit.tagName !== 'FRAME') break;
|
|
1289
|
+
let childDoc = null, childWin = null;
|
|
1290
|
+
try { childDoc = hit.contentDocument; childWin = hit.contentWindow; } catch {}
|
|
1291
|
+
if (!childDoc || !childWin) { unobservable = true; break; }
|
|
1292
|
+
wins.push([typeof WeakRef === 'function' ? new WeakRef(childWin) : childWin, childWin.scrollX || 0, childWin.scrollY || 0]);
|
|
1293
|
+
if (childDoc.scrollingElement) trackAncestors(childDoc.scrollingElement);
|
|
1294
|
+
const view = hit.ownerDocument?.defaultView || window;
|
|
1295
|
+
if (hasComplexTransform(hit, view)) { unobservable = true; break; }
|
|
1296
|
+
const r = hit.getBoundingClientRect ? hit.getBoundingClientRect() : null;
|
|
1297
|
+
if (!r || r.width <= 0 || r.height <= 0) { unobservable = true; break; }
|
|
1298
|
+
const st = typeof view.getComputedStyle === 'function' ? view.getComputedStyle(hit) : null;
|
|
1299
|
+
const sx = hit.offsetWidth > 0 ? r.width / hit.offsetWidth : 1;
|
|
1300
|
+
const sy = hit.offsetHeight > 0 ? r.height / hit.offsetHeight : 1;
|
|
1301
|
+
if (!(sx > 0) || !(sy > 0)) { unobservable = true; break; }
|
|
1302
|
+
const padL = parseFloat(st?.paddingLeft) || 0, padT = parseFloat(st?.paddingTop) || 0;
|
|
1303
|
+
px = Math.round((px - (r.left || 0)) / sx - (hit.clientLeft || 0) - padL);
|
|
1304
|
+
py = Math.round((py - (r.top || 0)) / sy - (hit.clientTop || 0) - padT);
|
|
1305
|
+
doc = childDoc;
|
|
1306
|
+
}
|
|
1307
|
+
window.__dshScrollCheck = { list, wins, unobservable };
|
|
1308
|
+
return { x: window.scrollX || 0, y: Math.round(window.scrollY || 0) };
|
|
1309
|
+
})()`
|
|
1310
|
+
const readScrollJs = `(() => {
|
|
1311
|
+
const check = window.__dshScrollCheck || {};
|
|
1312
|
+
let innerMoved = Boolean(check.unobservable);
|
|
1313
|
+
if (!innerMoved) {
|
|
1314
|
+
for (const item of check.list || []) {
|
|
1315
|
+
const el = item[0] && typeof item[0].deref === 'function' ? item[0].deref() : item[0];
|
|
1316
|
+
if (el && ((el.scrollLeft || 0) !== item[1] || (el.scrollTop || 0) !== item[2])) { innerMoved = true; break; }
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
if (!innerMoved) {
|
|
1320
|
+
for (const item of check.wins || []) {
|
|
1321
|
+
const w = item[0] && typeof item[0].deref === 'function' ? item[0].deref() : item[0];
|
|
1322
|
+
if (w && ((w.scrollX || 0) !== item[1] || (w.scrollY || 0) !== item[2])) { innerMoved = true; break; }
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return { scrollX: window.scrollX || 0, scrollY: Math.round(window.scrollY || 0), pageHeight: Math.round(document.documentElement.scrollHeight), innerMoved };
|
|
1326
|
+
})()`
|
|
1327
|
+
const before = await evaluate(tabId, snapScrollJs, false, budget(), guard)
|
|
1328
|
+
const beforeX = Number(before?.x ?? before?.scrollX ?? 0) || 0
|
|
1329
|
+
const beforeY = Number(before?.y ?? before?.scrollY ?? before) || 0
|
|
1330
|
+
guard()
|
|
1331
|
+
if (!noCursor && S.showCursor) {
|
|
1332
|
+
if (!S.cursorReady.has(id)) {
|
|
1333
|
+
await cursorMove(tabId, x, y, { duration: 0, agentMs: 1500, deadline: cursorDeadline() }).catch((e) => {
|
|
1334
|
+
if (dl !== undefined) throw e
|
|
1335
|
+
return null
|
|
1336
|
+
})
|
|
1337
|
+
}
|
|
1338
|
+
guard()
|
|
1339
|
+
if (S.cursorReady.has(id)) {
|
|
1340
|
+
await cursorFx(tabId, `(window.__dshCursor.beginAgent && window.__dshCursor.beginAgent(1500), window.__dshCursor.label(${JSON.stringify(deltaY < 0 ? labels[S.UI_LANG].up : labels[S.UI_LANG].down)}, 1400), window.__dshCursor.scroll(${deltaY < 0 ? -1 : 1}), 1)`, cursorDeadline()).catch((e) => {
|
|
1341
|
+
if (dl !== undefined) throw e
|
|
1342
|
+
return undefined
|
|
1343
|
+
})
|
|
1344
|
+
if (S.cursorReady.has(id)) S.pageAgentUntil.set(id, Date.now() + 1500)
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
if (beforePress) await beforePress()
|
|
1348
|
+
await verifyFrames()
|
|
1349
|
+
pGuard()
|
|
536
1350
|
await sendNoReply(tabId, 'Input.dispatchMouseEvent', {
|
|
537
1351
|
type: 'mouseWheel', x: Math.round(x), y: Math.round(y),
|
|
538
1352
|
deltaX: Math.round(deltaX), deltaY: Math.round(deltaY),
|
|
539
|
-
})
|
|
540
|
-
|
|
1353
|
+
}, 60, pGuard)
|
|
1354
|
+
guard()
|
|
1355
|
+
let after = await evaluate(tabId, readScrollJs, false, budget(), guard)
|
|
541
1356
|
let via = 'wheel'
|
|
542
|
-
|
|
1357
|
+
const unchanged = (s) => !s?.innerMoved && (deltaX ? s?.scrollY === beforeY && s?.scrollX === beforeX : s?.scrollY === beforeY)
|
|
1358
|
+
if (unchanged(after)) {
|
|
1359
|
+
await sleep(25)
|
|
1360
|
+
guard()
|
|
1361
|
+
after = await evaluate(tabId, readScrollJs, false, budget(), guard)
|
|
1362
|
+
}
|
|
1363
|
+
if (unchanged(after)) {
|
|
1364
|
+
guard()
|
|
543
1365
|
// 后台/不可见标签页里 Chrome 不会为滚轮合成帧(实测 mouseWheel 事件发了但页面不动),
|
|
544
1366
|
// 退回 JS 滚动 —— 想要的效果是"页面滚下去",不是"必须是合成事件"。
|
|
545
|
-
after = await evaluate(tabId, `(() => { window.scrollBy(
|
|
1367
|
+
after = await evaluate(tabId, `(() => { delete window.__dshScrollCheck; window.scrollBy(${Math.round(deltaX)}, ${Math.round(deltaY)}); return { scrollY: Math.round(window.scrollY), pageHeight: Math.round(document.documentElement.scrollHeight) } })()`, false, budget(), guard)
|
|
546
1368
|
via = 'js'
|
|
1369
|
+
} else {
|
|
1370
|
+
await evaluate(tabId, 'delete window.__dshScrollCheck', false, budget(), guard).catch(() => {})
|
|
547
1371
|
}
|
|
1372
|
+
delete after.innerMoved
|
|
548
1373
|
return { deltaY, via, ...after }
|
|
549
1374
|
},
|
|
550
1375
|
|
|
@@ -635,19 +1460,65 @@ const OPS = {
|
|
|
635
1460
|
},
|
|
636
1461
|
|
|
637
1462
|
/** 被 alert/confirm 挡住时用这个放行,否则页面会一直卡住 */
|
|
638
|
-
async dialog({ tabId, action, text }) {
|
|
1463
|
+
async dialog({ tabId, action, text, receipt = false, controlEpoch }) {
|
|
1464
|
+
const id = Number(tabId)
|
|
1465
|
+
const epoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0), globalEpoch = S.releaseAllEpoch
|
|
1466
|
+
const startSeq = S.attached.has(id) ? S.attachSeq.get(id) : null
|
|
1467
|
+
const guard = () => {
|
|
1468
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
1469
|
+
if (S.releasing.has(id) || (S.controlEpoch.get(id) || 0) !== epoch || globalEpoch !== S.releaseAllEpoch) throw new Error(RELEASED_MSG)
|
|
1470
|
+
if (startSeq && (!S.attached.has(id) || S.attachSeq.get(id) !== startSeq)) throw new Error(RELEASED_MSG)
|
|
1471
|
+
}
|
|
1472
|
+
guard()
|
|
1473
|
+
const beforeNavGen = S.mainNavGeneration.get(id) || 0
|
|
1474
|
+
const before = receipt ? { ...(await pageAccess(id, { frames: false })), selfOrigin: '', navGeneration: beforeNavGen } : null
|
|
1475
|
+
guard()
|
|
639
1476
|
const accept = action !== 'dismiss'
|
|
640
|
-
await send(tabId, 'Page.handleJavaScriptDialog', { accept, ...(text !== undefined ? { promptText: String(text) } : {}) })
|
|
641
|
-
S.dialogs.delete(
|
|
642
|
-
|
|
1477
|
+
await send(tabId, 'Page.handleJavaScriptDialog', { accept, ...(text !== undefined ? { promptText: String(text) } : {}) }, undefined, guard)
|
|
1478
|
+
S.dialogs.delete(id)
|
|
1479
|
+
const out = { action: accept ? 'accept' : 'dismiss' }
|
|
1480
|
+
if (receipt) {
|
|
1481
|
+
if (S.paused || S.releasing.has(id) || !S.attached.has(id) ||
|
|
1482
|
+
(startSeq && S.attachSeq.get(id) !== startSeq) ||
|
|
1483
|
+
(S.controlEpoch.get(id) || 0) !== epoch || globalEpoch !== S.releaseAllEpoch) {
|
|
1484
|
+
out.receipt = { beforeUrl: before?.url || '', beforeTitle: before?.title || '', url: before?.url || '', title: before?.title || '',
|
|
1485
|
+
navigated: false, originChanged: false, protectedSite: false, pendingDialog: null, liveUpdate: null, unverified: true,
|
|
1486
|
+
controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
1487
|
+
} else {
|
|
1488
|
+
try {
|
|
1489
|
+
const after = await receiptState(id, Date.now() + 1500, guard, [], before?.url ? originOf(before.url) : undefined, before?.url)
|
|
1490
|
+
out.receipt = receiptOf(id, before || { url: '', title: '', live: [] }, after)
|
|
1491
|
+
} catch {
|
|
1492
|
+
out.receipt = { beforeUrl: before?.url || '', beforeTitle: before?.title || '', url: before?.url || '', title: before?.title || '',
|
|
1493
|
+
navigated: false, originChanged: false, protectedSite: false, pendingDialog: null, liveUpdate: null, unverified: true,
|
|
1494
|
+
controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
return out
|
|
643
1499
|
},
|
|
644
1500
|
|
|
645
|
-
async key({ tabId, key, times = 1, chooser }) {
|
|
646
|
-
|
|
1501
|
+
async key({ tabId, key, times = 1, chooser, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: optNavGen, releaseBinding, releaseNavGen } = {}) {
|
|
1502
|
+
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
1503
|
+
const navGen = Number.isInteger(optNavGen) ? optNavGen : (Number.isInteger(expectedNavGen) ? expectedNavGen : undefined)
|
|
1504
|
+
const relGen = releaseNavGen ?? navGen ?? (S.mainNavGeneration.get(Number(tabId)) || 0)
|
|
1505
|
+
const fg = resolveFrameGuards(tabId, dl, check, pressCheck, verifyFrames, verifyFramesOnly, navGen)
|
|
1506
|
+
const guard = fg.guard, pGuard = fg.pGuard
|
|
1507
|
+
verifyFrames = fg.verifyFrames; verifyFramesOnly = fg.verifyFramesOnly
|
|
1508
|
+
guard()
|
|
1509
|
+
await (dl !== undefined ? within(ensure(tabId), timeLeft(dl), '等待调试器超时') : ensure(tabId))
|
|
1510
|
+
guard()
|
|
647
1511
|
// 焦点在「上传」按钮上按回车 / 空格也会弹选文件窗口
|
|
648
1512
|
return withChooser(tabId, chooser, async () => {
|
|
649
1513
|
const out = []
|
|
650
|
-
for (let i = 0; i < times; i++)
|
|
1514
|
+
for (let i = 0; i < times; i++) {
|
|
1515
|
+
if (beforePress) await beforePress()
|
|
1516
|
+
await verifyFrames()
|
|
1517
|
+
pGuard()
|
|
1518
|
+
const r = await pressKey(tabId, key, { deadline: dl, check: pGuard, verifyFramesOnly, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen })
|
|
1519
|
+
out.push(r)
|
|
1520
|
+
if (r?.navigated) break
|
|
1521
|
+
}
|
|
651
1522
|
return { pressed: key, times, modifiers: out[0] && out[0].modifiers }
|
|
652
1523
|
})
|
|
653
1524
|
},
|
|
@@ -663,13 +1534,17 @@ const OPS = {
|
|
|
663
1534
|
if (!el) return null;
|
|
664
1535
|
el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
665
1536
|
// 后台标签页会暂停 rAF —— 只等 rAF 会卡满 15 秒,定时器兜底(同 __dsh_point)
|
|
666
|
-
return new Promise((res) => {
|
|
1537
|
+
return new Promise((res, rej) => {
|
|
667
1538
|
let done = false;
|
|
668
1539
|
const finish = () => {
|
|
669
1540
|
if (done) return;
|
|
670
1541
|
done = true;
|
|
671
|
-
|
|
672
|
-
|
|
1542
|
+
try {
|
|
1543
|
+
const r = el.getBoundingClientRect();
|
|
1544
|
+
const sx = typeof window !== 'undefined' ? (Number(window.scrollX || window.pageXOffset) || 0) : 0;
|
|
1545
|
+
const sy = typeof window !== 'undefined' ? (Number(window.scrollY || window.pageYOffset) || 0) : 0;
|
|
1546
|
+
res({ x: r.left + sx, y: r.top + sy, width: r.width, height: r.height });
|
|
1547
|
+
} catch (err) { rej(err); }
|
|
673
1548
|
};
|
|
674
1549
|
requestAnimationFrame(() => requestAnimationFrame(finish));
|
|
675
1550
|
setTimeout(finish, 120);
|
|
@@ -791,11 +1666,15 @@ const OPS = {
|
|
|
791
1666
|
},
|
|
792
1667
|
|
|
793
1668
|
/** 页内光标只加载包内资源。script 字段仅兼容旧协议。 */
|
|
794
|
-
async cursor({ tabId, action, x, y, duration, straight, text }) {
|
|
1669
|
+
async cursor({ tabId, action, x, y, duration, straight, text, controlEpoch }) {
|
|
795
1670
|
const id = Number(tabId)
|
|
1671
|
+
const check = Number.isInteger(controlEpoch)
|
|
1672
|
+
? () => { if ((S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG) }
|
|
1673
|
+
: undefined
|
|
1674
|
+
if (check) check()
|
|
796
1675
|
if (action === 'hide' || action === 'clear') {
|
|
797
1676
|
try { await evaluate(tabId, 'window.__dshCursor && window.__dshCursor.hide()') }
|
|
798
|
-
finally { S.cursorReady.delete(id); S.cursorPos.delete(id); await markCursor(tabId, false) }
|
|
1677
|
+
finally { S.cursorReady.delete(id); S.cursorPos.delete(id); S.pageAgentUntil.delete(id); await markCursor(tabId, false) }
|
|
799
1678
|
return { action }
|
|
800
1679
|
}
|
|
801
1680
|
if (!S.showCursor) return { action, skipped: '用户在弹窗里关了页内光标', duration: 0 }
|
|
@@ -805,6 +1684,7 @@ const OPS = {
|
|
|
805
1684
|
if (d === null) throw missing()
|
|
806
1685
|
if (action === 'click') {
|
|
807
1686
|
await settle(d)
|
|
1687
|
+
if (check) check()
|
|
808
1688
|
await cursorDo(tabId, `(window.__dshCursor.click(${Math.round(x)}, ${Math.round(y)}), 1)`)
|
|
809
1689
|
}
|
|
810
1690
|
return { action, x, y, duration: d }
|