dsh-chrome-bridge 2.0.3 → 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 +8 -1
- 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 +10 -10
- package/features/frames.js +5 -2
- package/i18n/en.js +34 -7
- package/i18n/ru.js +34 -7
- package/i18n/zh.js +34 -7
- package/nav.js +103 -32
- package/package.json +1 -1
- package/refs.js +309 -73
- package/tools/batch.js +311 -0
- package/tools/click.js +37 -11
- package/tools/dialog.js +19 -2
- package/tools/drag.js +31 -5
- 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/tabs.js +16 -2
- package/tools/wait.js +14 -6
- package/vendor/extension/in-page-cursor.js +1 -1
- 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 +2 -1
- package/vendor/extension/sw/cdp.js +139 -11
- package/vendor/extension/sw/conditions.js +176 -0
- package/vendor/extension/sw/confirm.js +39 -7
- package/vendor/extension/sw/cursor.js +176 -14
- package/vendor/extension/sw/dispatch.js +6 -1
- package/vendor/extension/sw/frames.js +543 -47
- package/vendor/extension/sw/lifecycle.js +82 -0
- package/vendor/extension/sw/ops.js +801 -139
- package/vendor/extension/sw/page-access.js +292 -0
- package/vendor/extension/sw/popup-api.js +28 -7
- package/vendor/extension/sw/snapshot.js +251 -0
- package/vendor/extension/sw/state.js +16 -5
- package/vendor/extension/sw/tabui.js +9 -2
- package/vendor/in-page-cursor.js +1 -1
- package/vendor/skill/SKILL.md +8 -7
|
@@ -8,12 +8,17 @@ import {
|
|
|
8
8
|
} from './chooser.js'
|
|
9
9
|
import {
|
|
10
10
|
agentInput, agentInputKinds, bumpControlEpoch, clickPoint, cursorDo, cursorFx, cursorMove, injectCursor,
|
|
11
|
-
makeClickGuard, markCursor, mountHandoff, pressKey, RELEASED_MSG, settle, unmountHandoff,
|
|
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 { isSensitiveField } from './frames.js'
|
|
16
|
-
import { buildState, diagnostics, releaseAllTabs, setOwnWindow, setPaused, setShowCursor } from './popup-api.js'
|
|
20
|
+
import { isSensitiveField, sensitiveValue } from './frames.js'
|
|
21
|
+
import { buildState, diagnostics, releaseAllTabs, setOwnWindow, setPaused, setShowCursor, setCursorPace } from './popup-api.js'
|
|
17
22
|
import { CHOOSER_TTL_MS, PAUSED_MSG, S } from './state.js'
|
|
18
23
|
import { labels, unmarkTab } from './tabui.js'
|
|
19
24
|
import { checkPath, isExtUrl, sleep, timeLeft, updateBadge, within } from './util.js'
|
|
@@ -51,7 +56,60 @@ async function protectedFilter(items, checkCurrentTab = true) {
|
|
|
51
56
|
return (x) => tabOk.get(x.tabId) === true && itemAllowed(x)
|
|
52
57
|
}
|
|
53
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
|
+
|
|
54
111
|
const OPS = {
|
|
112
|
+
act, dragGesture, waitCondition, snapshotScan,
|
|
55
113
|
async diagnostics() {
|
|
56
114
|
const state = await buildState()
|
|
57
115
|
const { version, connected, paused, pauseReason, disconnectReason, attachedCount, showCursor, ownWindow, sessions } = state
|
|
@@ -94,21 +152,76 @@ const OPS = {
|
|
|
94
152
|
}
|
|
95
153
|
},
|
|
96
154
|
|
|
97
|
-
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 }) {
|
|
98
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)
|
|
99
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
|
+
}
|
|
100
200
|
while (Date.now() - at < timeoutMs) {
|
|
101
|
-
|
|
201
|
+
guard()
|
|
102
202
|
const waitedMs = Date.now() - at
|
|
103
203
|
if (urlFilter) {
|
|
104
204
|
const hit = S.NET.find(r => r.tabId === id && r.at >= (since ?? at - 30000) && r.url.includes(urlFilter) && (!hasProtectedSites() || itemAllowed(r)))
|
|
105
|
-
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 })
|
|
106
206
|
} else {
|
|
107
207
|
const busy = [...S.netPending.values()].some(r => r.tabId === id && r.type !== 'WebSocket' && r.type !== 'EventSource')
|
|
108
|
-
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
|
+
}
|
|
109
211
|
}
|
|
110
212
|
await sleep(Math.min(100, timeoutMs - waitedMs))
|
|
111
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
|
+
}
|
|
112
225
|
throw new Error('等待网络超时')
|
|
113
226
|
},
|
|
114
227
|
|
|
@@ -162,7 +275,8 @@ const OPS = {
|
|
|
162
275
|
},
|
|
163
276
|
|
|
164
277
|
async version() {
|
|
165
|
-
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 } }
|
|
166
280
|
},
|
|
167
281
|
|
|
168
282
|
/**
|
|
@@ -170,12 +284,13 @@ const OPS = {
|
|
|
170
284
|
* 只开放「更安全」的方向:这条通道 DSH 里的模型也摸得到(cb / socket),
|
|
171
285
|
* 所以「恢复控制」不给 —— 那一下只能用户在 Chrome 的扩展面板里点。
|
|
172
286
|
*/
|
|
173
|
-
async panel({ action = 'state', on } = {}) {
|
|
287
|
+
async panel({ action = 'state', on, cursorPace } = {}) {
|
|
174
288
|
if (action === 'pause') {
|
|
175
289
|
if (!on) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 面板里打开')
|
|
176
290
|
await setPaused(true, 'panel')
|
|
177
291
|
} else if (action === 'cursor') {
|
|
178
|
-
await
|
|
292
|
+
if (cursorPace !== undefined) await setCursorPace(cursorPace, 'DSH 设置页')
|
|
293
|
+
else await setShowCursor(!!on, 'DSH 设置页')
|
|
179
294
|
} else if (action === 'window') {
|
|
180
295
|
await setOwnWindow(!!on, 'DSH 设置页')
|
|
181
296
|
} else if (action === 'releaseAll') {
|
|
@@ -185,7 +300,7 @@ const OPS = {
|
|
|
185
300
|
}
|
|
186
301
|
const st = await buildState()
|
|
187
302
|
return {
|
|
188
|
-
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,
|
|
189
304
|
ownWindow: st.ownWindow, attachedCount: st.attachedCount, pauseReason: st.pauseReason, handoff: st.handoff,
|
|
190
305
|
protectedCount: Array.isArray(st.protectedSites) ? st.protectedSites.length : 0,
|
|
191
306
|
sessions: st.sessions.filter((x) => x.tabs.some((t) => t.attached)).length,
|
|
@@ -247,20 +362,28 @@ const OPS = {
|
|
|
247
362
|
|
|
248
363
|
/** 第二个参数只给扩展内部用(dispatch 只传 args):空闲自动断开传 reason 'idle',受保护网站的放行就不跟着作废 */
|
|
249
364
|
async detach({ tabId }, { reason = 'detached' } = {}) {
|
|
250
|
-
|
|
251
|
-
if (
|
|
252
|
-
S.
|
|
253
|
-
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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)
|
|
386
|
+
}
|
|
264
387
|
},
|
|
265
388
|
|
|
266
389
|
async activate({ tabId }) {
|
|
@@ -270,17 +393,105 @@ const OPS = {
|
|
|
270
393
|
return { tabId: Number(tabId), windowId: t.windowId }
|
|
271
394
|
},
|
|
272
395
|
|
|
273
|
-
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
|
|
274
399
|
// 相对地址会被 tabs.create 按扩展自己的地址补全(example.com → chrome-extension://…/example.com),只收完整网址
|
|
275
400
|
if (url) { try { new URL(url) } catch { throw new Error(`要给完整网址(带 https://):${url}`) } }
|
|
276
401
|
// 默认开进 DSH 自己的窗口(后台,不抢焦点);用户关了「单独窗口」就在当前窗口后台开页。
|
|
277
402
|
// 两种都不顶掉用户正在看的标签页。active=true(cb open --front)是有意要它跳到眼前,照旧开在当前窗口
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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
|
+
}
|
|
281
423
|
}
|
|
282
|
-
const
|
|
283
|
-
|
|
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
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return out
|
|
284
495
|
},
|
|
285
496
|
|
|
286
497
|
async close({ tabId }) {
|
|
@@ -288,31 +499,46 @@ const OPS = {
|
|
|
288
499
|
return { closed: Number(tabId) }
|
|
289
500
|
},
|
|
290
501
|
|
|
291
|
-
async eval({ tabId, expression, userGesture = false, timeoutMs, controlEpoch, requireControl = false }) {
|
|
502
|
+
async eval({ tabId, expression, userGesture = false, timeoutMs, controlEpoch, requireControl = false, noReattach = false }) {
|
|
292
503
|
const id = Number(tabId)
|
|
293
504
|
const startEpoch = S.controlEpoch.get(id) || 0
|
|
294
505
|
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
295
|
-
const check = (Number.isInteger(controlEpoch) || requireControl)
|
|
506
|
+
const check = (Number.isInteger(controlEpoch) || requireControl || noReattach)
|
|
296
507
|
? makeClickGuard(tabId, dl, () => {
|
|
508
|
+
if (noReattach && !S.attached.has(id)) throw new Error(RELEASED_MSG)
|
|
297
509
|
if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
|
|
298
510
|
if (requireControl && (S.controlEpoch.get(id) || 0) !== startEpoch) throw new Error(RELEASED_MSG)
|
|
299
511
|
})
|
|
300
512
|
: undefined
|
|
301
513
|
if (check) check()
|
|
302
514
|
const value = await evaluate(tabId, expression, userGesture === true, timeoutMs, check)
|
|
303
|
-
if (requireControl && check) check()
|
|
304
|
-
return { value, controlEpoch: startEpoch }
|
|
515
|
+
if ((requireControl || noReattach) && check) check()
|
|
516
|
+
return { value, controlEpoch: startEpoch, navGeneration: S.mainNavGeneration.get(id) || 0 }
|
|
305
517
|
},
|
|
306
518
|
|
|
307
|
-
async cdp({ tabId, method, params, timeoutMs, controlEpoch, releaseOnlyForAttachSeq }) {
|
|
519
|
+
async cdp({ tabId, method, params, timeoutMs, controlEpoch, noReattach = false, releaseOnlyForAttachSeq }) {
|
|
308
520
|
const id = Number(tabId)
|
|
309
521
|
if (Number.isInteger(releaseOnlyForAttachSeq) && method === 'Input.dispatchMouseEvent' && params?.type === 'mouseReleased') {
|
|
310
|
-
|
|
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')
|
|
311
534
|
const r = await chrome.debugger.sendCommand({ tabId: id }, method, params || {})
|
|
312
|
-
return { result: r, attachSeq: S.attachSeq.get(id) || 0 }
|
|
535
|
+
return { result: r, attachSeq: S.attachSeq.get(id) || 0, controlEpoch: S.controlEpoch.get(id) || 0 }
|
|
313
536
|
}
|
|
314
|
-
const check = Number.isInteger(controlEpoch)
|
|
315
|
-
? () => {
|
|
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
|
+
}
|
|
316
542
|
: undefined
|
|
317
543
|
if (check) check()
|
|
318
544
|
checkCdp(method, params)
|
|
@@ -340,62 +566,172 @@ const OPS = {
|
|
|
340
566
|
}
|
|
341
567
|
}
|
|
342
568
|
const meta = {}
|
|
343
|
-
|
|
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 }
|
|
344
575
|
},
|
|
345
576
|
|
|
346
|
-
async
|
|
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 }
|
|
610
|
+
},
|
|
611
|
+
|
|
612
|
+
async nav({ tabId, url, wait = 'load', timeoutMs = 30000, receipt = false }) {
|
|
613
|
+
const phase = waitPhase(wait)
|
|
347
614
|
const deadline = Date.now() + timeoutMs
|
|
348
|
-
const id =
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
clearTimeout(entry.timer)
|
|
358
|
-
entries.delete(entry)
|
|
359
|
-
if (!entries.size) S.loadWaiters.delete(id)
|
|
360
|
-
resolve(value)
|
|
361
|
-
} }
|
|
362
|
-
entries.add(entry)
|
|
363
|
-
S.loadWaiters.set(id, entries)
|
|
364
|
-
entry.timer = setTimeout(() => entry.finish(false), waitMs)
|
|
365
|
-
})
|
|
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)
|
|
366
624
|
let r, loaded = null
|
|
367
625
|
try {
|
|
368
|
-
r = await send(id, 'Page.navigate', { url }, timeLeft(deadline))
|
|
626
|
+
r = await send(id, 'Page.navigate', { url }, timeLeft(deadline), guard)
|
|
369
627
|
if (r.errorText) throw new Error(r.errorText)
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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,
|
|
691
|
+
}
|
|
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
|
|
385
712
|
},
|
|
386
713
|
|
|
387
|
-
async click({ tabId, x, y, clickCount, button, chooser, noCursor, timeoutMs }) {
|
|
388
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
389
|
-
const
|
|
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)
|
|
390
722
|
return clickPoint(tabId, x, y, {
|
|
391
|
-
deadline: dl, check: guard, clickCount, button, chooser,
|
|
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,
|
|
392
724
|
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} (${Math.round(x)}, ${Math.round(y)})` },
|
|
393
725
|
})
|
|
394
726
|
},
|
|
395
727
|
|
|
396
|
-
async clickEl({ tabId, selector, chooser, clickCount, button, noCursor, timeoutMs }, { 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 } = {}) {
|
|
397
729
|
const dl = deadline ?? (timeoutMs != null ? Date.now() + timeoutMs : undefined)
|
|
398
|
-
const
|
|
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
|
|
399
735
|
const pt = await pointOf(tabId, `
|
|
400
736
|
const el = document.querySelector(${JSON.stringify(selector)});
|
|
401
737
|
if (!el) return null;
|
|
@@ -406,18 +742,96 @@ const OPS = {
|
|
|
406
742
|
if (inner) target = inner;
|
|
407
743
|
}
|
|
408
744
|
if (!__dsh_visible(target) && !target.getBoundingClientRect().width) return null;
|
|
409
|
-
|
|
410
|
-
|
|
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
|
+
}
|
|
411
821
|
const hit = await clickPoint(tabId, pt.x, pt.y, {
|
|
412
|
-
deadline: dl, check: guard, clickCount, button, chooser,
|
|
822
|
+
deadline: dl, check: guard, pressCheck: pGuard, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen, clickCount, button, chooser,
|
|
413
823
|
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` },
|
|
414
824
|
})
|
|
415
825
|
return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
|
|
416
826
|
},
|
|
417
827
|
|
|
418
|
-
async clickText({ tabId, text, exact = true, index = 0, chooser, clickCount, button, noCursor, timeoutMs }) {
|
|
419
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
420
|
-
const
|
|
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
|
|
421
835
|
const pt = await pointOf(tabId, `
|
|
422
836
|
const want = __dsh_norm(${JSON.stringify(text)});
|
|
423
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';
|
|
@@ -470,10 +884,19 @@ const OPS = {
|
|
|
470
884
|
const pl = pr.left != null ? pr.left : pr.x, pt0 = pr.top != null ? pr.top : pr.y;
|
|
471
885
|
const cov = __dsh_cover(el, cx, cy);
|
|
472
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));
|
|
473
896
|
window.__dshClickTextTarget = {
|
|
474
897
|
el: typeof WeakRef === 'function' ? new WeakRef(el) : el,
|
|
475
898
|
textNode: typeof WeakRef === 'function' ? new WeakRef(liveNode) : liveNode,
|
|
476
|
-
cover: covHit ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
899
|
+
cover: covHit && !isAnc ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
477
900
|
};
|
|
478
901
|
return { ...cov, x: cx, y: cy,
|
|
479
902
|
text: (el.innerText || '').trim().slice(0, 60), tag: el.tagName.toLowerCase(),
|
|
@@ -483,17 +906,27 @@ const OPS = {
|
|
|
483
906
|
const ex = pr.left + pr.width / 2, ey = pr.top + pr.height / 2;
|
|
484
907
|
const cov = __dsh_cover(el, ex, ey);
|
|
485
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));
|
|
486
918
|
window.__dshClickTextTarget = {
|
|
487
919
|
el: typeof WeakRef === 'function' ? new WeakRef(el) : el,
|
|
488
920
|
textNode: null,
|
|
489
|
-
cover: covHit ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
921
|
+
cover: covHit && !isAnc2 ? (typeof WeakRef === 'function' ? new WeakRef(covHit) : covHit) : null,
|
|
490
922
|
};
|
|
491
923
|
return { ...cov, x: ex, y: ey, tag: el.tagName.toLowerCase(),
|
|
492
924
|
text: __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') ||
|
|
493
925
|
el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) };
|
|
494
|
-
`, dl)
|
|
926
|
+
`, dl, guard)
|
|
495
927
|
// mouseMoved 后、mousePressed 前始终核对坐标命中元素,防止遮挡消失或悬停重排后误点同行/邻行同名按钮
|
|
496
928
|
const beforePress = async () => {
|
|
929
|
+
if (extraBeforePress) await extraBeforePress()
|
|
497
930
|
const ok = await evaluate(tabId, `(() => {
|
|
498
931
|
const ref = window.__dshClickTextTarget;
|
|
499
932
|
delete window.__dshClickTextTarget;
|
|
@@ -512,8 +945,9 @@ const OPS = {
|
|
|
512
945
|
return false;
|
|
513
946
|
};
|
|
514
947
|
const deref = (r) => (r && typeof r.deref === 'function' ? r.deref() : r);
|
|
515
|
-
|
|
516
|
-
const
|
|
948
|
+
if (!ref) return false;
|
|
949
|
+
const el = deref(ref.el);
|
|
950
|
+
const cov = deref(ref.cover);
|
|
517
951
|
if (!el || el.isConnected === false) return false;
|
|
518
952
|
if (!match(label(el))) return false;
|
|
519
953
|
if (ref.textNode) {
|
|
@@ -524,10 +958,39 @@ const OPS = {
|
|
|
524
958
|
}
|
|
525
959
|
}
|
|
526
960
|
if (typeof document.elementFromPoint === 'function') {
|
|
527
|
-
const
|
|
961
|
+
const px = ${Math.round(pt.x)}, py = ${Math.round(pt.y)};
|
|
962
|
+
const hit = document.elementFromPoint(px, py);
|
|
528
963
|
if (!hit) return false;
|
|
529
|
-
const
|
|
530
|
-
|
|
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);
|
|
531
994
|
if (!onTarget && !onSameCover) return false;
|
|
532
995
|
}
|
|
533
996
|
return true;
|
|
@@ -535,26 +998,45 @@ const OPS = {
|
|
|
535
998
|
if (!ok) throw new Error('目标文字在点击前已变化,已中止点击')
|
|
536
999
|
}
|
|
537
1000
|
const hit = await clickPoint(tabId, pt.x, pt.y, {
|
|
538
|
-
deadline: dl, check: guard, beforePress, clickCount, button, chooser,
|
|
1001
|
+
deadline: dl, check: guard, pressCheck: pGuard, verifyFrames, verifyFramesOnly, beforePress, docBinding, expectedNavGen: navGen, releaseBinding, releaseNavGen: relGen, clickCount, button, chooser,
|
|
539
1002
|
cursor: noCursor ? null : { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` },
|
|
540
1003
|
})
|
|
541
1004
|
return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
|
|
542
1005
|
},
|
|
543
1006
|
|
|
544
|
-
async type({ tabId, text, selector, noCursor, timeoutMs }) {
|
|
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 } = {}) {
|
|
545
1008
|
const id = Number(tabId)
|
|
546
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
547
|
-
const
|
|
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() }
|
|
548
1016
|
const budget = () => (dl !== undefined ? timeLeft(dl) : undefined)
|
|
549
1017
|
const cursorDeadline = () => (dl !== undefined ? dl : Date.now() + 1500)
|
|
550
|
-
if (selector) await getOps().clickEl({ tabId, selector, noCursor, timeoutMs }, { deadline: dl, check: guard })
|
|
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 })
|
|
551
1019
|
guard()
|
|
552
1020
|
await (dl !== undefined ? within(ensure(tabId), budget(), '等待调试器超时') : ensure(tabId))
|
|
553
1021
|
guard()
|
|
554
1022
|
// 名牌写上在输什么。只有确认焦点落在普通(非密码)输入框里才亮原文:焦点在 shadow DOM / 同源 iframe 里
|
|
555
1023
|
// 就往里找真正的焦点元素;找不到(跨域 iframe、关闭的 shadow root……)或者是密码/验证码样式的框,一律打码
|
|
556
|
-
const sensitive =
|
|
557
|
-
|
|
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
|
+
}
|
|
558
1040
|
const shown = sensitive ? 'null' : JSON.stringify(text.length > 24 ? text.slice(0, 24) + '…' : text)
|
|
559
1041
|
if (!noCursor && S.showCursor) {
|
|
560
1042
|
if (!S.cursorReady.has(id)) {
|
|
@@ -618,7 +1100,42 @@ const OPS = {
|
|
|
618
1100
|
}
|
|
619
1101
|
}
|
|
620
1102
|
guard()
|
|
621
|
-
|
|
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
|
+
}
|
|
622
1139
|
return { typed: text.length, selector: selector || null }
|
|
623
1140
|
},
|
|
624
1141
|
|
|
@@ -648,19 +1165,28 @@ const OPS = {
|
|
|
648
1165
|
return { selector, name, value }
|
|
649
1166
|
},
|
|
650
1167
|
|
|
651
|
-
async info({ tabId }) {
|
|
652
|
-
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)
|
|
653
1177
|
let viewport = null
|
|
654
1178
|
try {
|
|
655
|
-
await ensure(tabId)
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
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
|
+
}
|
|
659
1185
|
} catch {}
|
|
660
1186
|
return {
|
|
661
|
-
tabId:
|
|
662
|
-
windowId: t.windowId, active: t.active, attached: S.attached.has(
|
|
663
|
-
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,
|
|
664
1190
|
}
|
|
665
1191
|
},
|
|
666
1192
|
|
|
@@ -685,36 +1211,122 @@ const OPS = {
|
|
|
685
1211
|
|
|
686
1212
|
// ── 输入类 ───────────────────────────────────────────────────────────────
|
|
687
1213
|
|
|
688
|
-
async hover({ tabId, x, y, selector, noCursor, timeoutMs }) {
|
|
689
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
690
|
-
const
|
|
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
|
|
691
1219
|
let px = Number(x) || 0, py = Number(y) || 0, target = null
|
|
692
1220
|
if (selector) {
|
|
693
|
-
const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el);`, dl)
|
|
1221
|
+
const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el);`, dl, guard)
|
|
694
1222
|
px = pt.x; py = pt.y; target = pt
|
|
695
1223
|
}
|
|
696
1224
|
guard()
|
|
697
1225
|
if (!noCursor && S.showCursor) {
|
|
698
|
-
|
|
1226
|
+
await moveForAction(tabId, px, py, {
|
|
1227
|
+
check: guard,
|
|
699
1228
|
label: `${labels[S.UI_LANG].hover} ${target ? target.text || target.tag : `(${Math.round(px)}, ${Math.round(py)})`}`,
|
|
700
1229
|
deadline: dl,
|
|
701
1230
|
agentMs: 1500,
|
|
702
1231
|
})
|
|
703
|
-
if (d !== null) await (dl !== undefined ? within(settle(d), timeLeft(dl), '等待光标超时') : settle(d))
|
|
704
1232
|
}
|
|
705
|
-
|
|
706
|
-
await
|
|
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)
|
|
707
1237
|
return { x: Math.round(px), y: Math.round(py), target }
|
|
708
1238
|
},
|
|
709
1239
|
|
|
710
|
-
async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0, noCursor, timeoutMs }) {
|
|
1240
|
+
async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0, noCursor, timeoutMs, expectedNavGen }, { deadline, check, pressCheck, verifyFrames, verifyFramesOnly, beforePress } = {}) {
|
|
711
1241
|
const id = Number(tabId)
|
|
712
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
713
|
-
const
|
|
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
|
|
714
1246
|
const budget = () => (dl !== undefined ? timeLeft(dl) : undefined)
|
|
715
1247
|
const cursorDeadline = () => (dl !== undefined ? dl : Date.now() + 1500)
|
|
716
1248
|
guard()
|
|
717
|
-
const
|
|
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
|
|
718
1330
|
guard()
|
|
719
1331
|
if (!noCursor && S.showCursor) {
|
|
720
1332
|
if (!S.cursorReady.has(id)) {
|
|
@@ -732,21 +1344,32 @@ const OPS = {
|
|
|
732
1344
|
if (S.cursorReady.has(id)) S.pageAgentUntil.set(id, Date.now() + 1500)
|
|
733
1345
|
}
|
|
734
1346
|
}
|
|
735
|
-
|
|
1347
|
+
if (beforePress) await beforePress()
|
|
1348
|
+
await verifyFrames()
|
|
1349
|
+
pGuard()
|
|
736
1350
|
await sendNoReply(tabId, 'Input.dispatchMouseEvent', {
|
|
737
1351
|
type: 'mouseWheel', x: Math.round(x), y: Math.round(y),
|
|
738
1352
|
deltaX: Math.round(deltaX), deltaY: Math.round(deltaY),
|
|
739
|
-
},
|
|
1353
|
+
}, 60, pGuard)
|
|
740
1354
|
guard()
|
|
741
|
-
let after = await evaluate(tabId,
|
|
1355
|
+
let after = await evaluate(tabId, readScrollJs, false, budget(), guard)
|
|
742
1356
|
let via = 'wheel'
|
|
743
|
-
|
|
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)) {
|
|
744
1364
|
guard()
|
|
745
1365
|
// 后台/不可见标签页里 Chrome 不会为滚轮合成帧(实测 mouseWheel 事件发了但页面不动),
|
|
746
1366
|
// 退回 JS 滚动 —— 想要的效果是"页面滚下去",不是"必须是合成事件"。
|
|
747
|
-
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)
|
|
748
1368
|
via = 'js'
|
|
1369
|
+
} else {
|
|
1370
|
+
await evaluate(tabId, 'delete window.__dshScrollCheck', false, budget(), guard).catch(() => {})
|
|
749
1371
|
}
|
|
1372
|
+
delete after.innerMoved
|
|
750
1373
|
return { deltaY, via, ...after }
|
|
751
1374
|
},
|
|
752
1375
|
|
|
@@ -837,16 +1460,51 @@ const OPS = {
|
|
|
837
1460
|
},
|
|
838
1461
|
|
|
839
1462
|
/** 被 alert/confirm 挡住时用这个放行,否则页面会一直卡住 */
|
|
840
|
-
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()
|
|
841
1476
|
const accept = action !== 'dismiss'
|
|
842
|
-
await send(tabId, 'Page.handleJavaScriptDialog', { accept, ...(text !== undefined ? { promptText: String(text) } : {}) })
|
|
843
|
-
S.dialogs.delete(
|
|
844
|
-
|
|
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
|
|
845
1499
|
},
|
|
846
1500
|
|
|
847
|
-
async key({ tabId, key, times = 1, chooser, timeoutMs }) {
|
|
848
|
-
const dl = timeoutMs != null ? Date.now() + timeoutMs : undefined
|
|
849
|
-
const
|
|
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
|
|
850
1508
|
guard()
|
|
851
1509
|
await (dl !== undefined ? within(ensure(tabId), timeLeft(dl), '等待调试器超时') : ensure(tabId))
|
|
852
1510
|
guard()
|
|
@@ -854,8 +1512,12 @@ const OPS = {
|
|
|
854
1512
|
return withChooser(tabId, chooser, async () => {
|
|
855
1513
|
const out = []
|
|
856
1514
|
for (let i = 0; i < times; i++) {
|
|
857
|
-
|
|
858
|
-
|
|
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
|
|
859
1521
|
}
|
|
860
1522
|
return { pressed: key, times, modifiers: out[0] && out[0].modifiers }
|
|
861
1523
|
})
|