forked from Xeo786/Rufaydium-Webdriver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCDP.ahk
607 lines (535 loc) · 13.5 KB
/
CDP.ahk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
; CDP.ahk provides access to Devtools over WebDriver that support Chrome DevTools
; CDP.ahk is exactly Chrome DOM.ahk >> https://www.autohotkey.com/boards/viewtopic.php?t=94276&p=418181
; by Xeo786
class CDP ;extends Rufaydium
{
__new(Address)
{
this.address := Address
root := this.call("DOM.getDocument",{"depth": 0}) ;this.call("DOM.getDocument",{"":""})
this.nodeId := root.root.nodeId
FrameData := this.call("Page.getFrameTree").frametree
if FrameData.frame
this.framedetail := FrameData.frame
if FrameData.childFrames
this.childFrames := FrameData.childFrames
}
FramesLength()
{
return this.childFrames.length()
}
Frame(i)
{
frameId := this.childFrames[i +1].frame.id
this.ParentNodeID := this.Nodeid
if frameId
{
nodeid := this.call("DOM.getFrameOwner",{"frameId":frameId}).nodeid
backendNodeId := this.call("DOM.describeNode",{"nodeId":nodeid}).node.contentDocument.backendNodeId
contentDocObject := this.call("DOM.resolveNode",{"backendNodeId":backendNodeId}).object.objectId
this.nodeid := this.call("DOM.requestNode",{"objectId":contentDocObject}).nodeId
}
}
ParentFrame()
{
this.Nodeid := this.ParentNodeID
}
send(url,Method,Payload:= 0,WaitForResponse:=1)
{
if !instr(url,"HTTP")
url := this.address "/" url
if !Payload and (Method = "POST")
Payload := Json.null
try r := Json.load(Rufaydium.Request(url,Method,Payload,WaitForResponse)).value ; Thanks to GeekDude for his awesome cJson.ahk
if(r.error = "chrome not reachable") ; incase someone close browser manually but session is not closed for driver
this.quit() ; so we close session for driver at cost of one time response wait lag
if r
return r
}
Call(DomainAndMethod, Params:="") ;https://stackoverflow.com/questions/70654898/selenium-4-x-trying-to-post-cdp-unsupportedcommandexception
{
Payload := { "params": Params ? Params : {"":""}, "cmd": DomainAndMethod}
response := this.Send("goog/cdp/execute"
,"POST"
,Payload
,1)
return response
}
Evaluate(JS)
{
response := this.Call("Runtime.evaluate",
( LTrim Join
{
"expression": JS,
"objectGroup": "console",
"includeCommandLineAPI": Json.true,
"silent": Json.false,
"returnByValue": Json.false,
"userGesture": Json.true,
"awaitPromise": Json.false
}
))
return response.result
}
Activate
{
set
{
Page.Call("Page.bringToFront")
}
}
GetlocalStorage(url)
{
LocalStoarge := this.call("DOMStorage.getDOMStorageItems",{"storageId":{"securityOrigin":url,"isLocalStorage":json.true}}).entries
enrties := {}
for k, v in LocalStoarge
{
key := "", Value := ""
for i, j in v
{
if i = 1
key := j
else if i = 2
Value := j
}
enrties[key] := Value
}
return enrties
}
createBrowserContext() ; create session
{
return this.call("Target.createBrowserContext")
}
disposeBrowserContext() ; close session and its all pages
{
return this.call("Target.disposeBrowserContext")
}
getBrowserContexts() ; Get sessions
{
return this.call("Target.getBrowserContexts")
}
CreateTarget(url) ; create new page with url
{
return this.call("Target.createTarget",{"url":url})
}
closeTarget(targetId) ; close page
{
return this.call("Target.closeTarget",{"targetId":targetId})
}
Switch(targetId) ; switch to page
{
;if Slient
return this.call("Target.activateTarget",{"targetId":targetId})
;else
; return this.call("Browser.getWindowForTarget",{"targetId":targetId})
}
GetTargets() ; get all sessions with Pages
{
return this.call("Target.getTargets")
}
AttachTarget(targetId) ; connect to disconnected page
{
return this.call("Target.attachToTarget",{"targetId":targetId})
}
DetachTarget(targetId) ; disconnect page
{
return this.call("Target.detachFromTarget",{"targetId":targetId})
}
requestNode(Objectid)
{
obj := this.call("DOM.requestNode",{"objectId":Objectid})
if obj.nodeId
this.nodeId := obj.nodeId
return obj
}
resolveNode()
{
Obj := this.call("DOM.resolveNode",{"nodeId":this.nodeId}).ObjectID
if Obj.objectId
this.ObjectID := Obj.objectId
return obj
}
Navigate(url)
{
return this.call("Page.navigate",{"url":url})
}
Reload() ; by https://github.com/hotcheesesoup
{
return this.call("Page.reload")
}
WaitForLoad(DesiredState:="complete", Interval:=100)
{
while this.Evaluate("document.readyState").value != DesiredState
{
Sleep, Interval
}
}
FindElement(Path)
{
return this.call("DOM.querySelector",{"nodeId":this.nodeId,"selector":path})
}
FindElements(Path)
{
return this.call("DOM.querySelectorAll",{"nodeId":this.nodeId,"selector":path})
}
querySelector(Path)
{
return New CDPElement(xx:=this.FindElement(Path).nodeId,this.address)
}
getElementByID(ID)
{
return New CDPElement(this.FindElement("#" ID).nodeId,this.address)
}
querySelectorAll(path)
{
e := []
for i, NodeID in this.FindElements(Path).nodeIDs
{
e[i -1] := New CDPElement(NodeID,this.address)
}
return e
}
getElementsbyClassName(Class)
{
e := []
path = [class='%Class%']
return this.querySelectorAll(path)
}
getElementsbyName(Name)
{
e := []
path = [Name='%Name%']
return this.querySelectorAll(path)
}
GetelementbyJS(JS)
{
result := this.Evaluate(JS)
if (result.className = "NodeList")
{
objectId := result.objectId
e := []
i := 0
results := this.call("Runtime.getProperties",{"objectId":Objectid}).result
for key, obj in results
{
for k, v in obj
{
if (v.subtype = "Node")
{
nodeId := this.call("DOM.requestNode",{"objectId":v.Objectid}).nodeId
e[i++] := New CDPElement(nodeId,this.address)
}
}
}
return e
}
else
{
objectId := result.objectId
nodeId := this.call("DOM.requestNode",{"objectId":Objectid}).nodeId
return New CDPElement(nodeId,this.address)
}
}
focus() ; simply focus on node element
{
this.call("DOM.focus",{"nodeId":this.nodeId})
}
getNodeForLocation(x,y)
{
nodeid := this.call("DOM.getNodeForLocation",{"x":x,"y":y}).nodeId
return New CDPElement(nodeId,this.address)
}
getBoxModel()
{ ;this return with model having Height and widths and x y coordinates of Margin padding and border
return this.call("DOM.getBoxModel",{"nodeId":this.nodeId}).model
}
getNodeQuads()
{ ; return quads are x immediately followed by y for each point, points clock-wise
return this.call("DOM.getContentQuads",{"nodeId":this.nodeId}).quads[1]
}
; this simply highlight borders of element but
; its slow because highlight element by location and extracting location feels little slow
highlightRect(r:=255,g:=0,b:=0,a:=1)
{
Model := this.getBoxModel()
height := Model.height
width := Model.width
; An array of quad vertices, x immediately followed by y for each point, points clock-wise.
content := Model.border ; getting content quad
toprightx := round(content[1],0)
toprighty := round(content[2],0)
color := {"r":r,"g":g,"b":b,"a":a}
this.call("Overlay.enable")
this.call("Overlay.highlightRect",{"x":toprightx,"y":toprighty,"width":width,"height":height,"outlineColor":color})
}
; highlight node Configurations:
; will be saved into the Element and will be triggered using element.highlight()
; Type = Solid or Grid
; Subtype for Solid are "contentColor","paddingColor","borderColor","marginColor","eventTargetColor","shapeColor","shapeMarginColor","cssGridColor"
; Subtype for Grid are "gridBorderColor","cellBorderColor","rowLineColor","columnLineColor"
highlightConfigurations(Type,Subtype,r,g,b,a)
{
Basetype := ["contentColor","paddingColor","borderColor","marginColor","eventTargetColor","shapeColor","shapeMarginColor","cssGridColor"]
Gridtype := ["gridBorderColor","cellBorderColor","rowLineColor","columnLineColor","rowGapColor","rowHatchColor","columnGapColor","columnHatchColor","areaBorderColor","gridBackgroundColor"]
if(Type = "Solid")
{
found := 0
for k, v in Basetype
{
if(Subtype == v)
found := 1
}
if found
{
this.highlightConfig[Subtype] := {"r":r,"g":g,"b":b,"a":a}
}
else
{
MsgBox 0x40010, , Wrong / missing subtype
}
}
else if(Type = "Grid")
{
found := 0
for k, v in Gridtype
{
if(Subtype == v)
found := 1
}
if found
{
this.highlightConfig.GridHighlightConfig[Subtype] := {"r":r,"g":g,"b":b,"a":a}
}
else
{
MsgBox 0x40010, , Wrong / missing subtype
}
}
else
{
MsgBox 0x40040, , Type Should be "Solid" or "Grid"
}
}
; setting up grid parameters true
GridSet(Param)
{
L := ["showGridExtensionLines"
,"showPositiveLineNumbers"
,"showNegativeLineNumbers"
,"showAreaNames"
,"showLineNames"
,"showTrackSizes"
,"gridBorderDash"
,"cellBorderDash"
,"rowLineDash"
,"columnLineDash"]
for k, v in L
{
if(Param = v)
found := 1
}
if found ;GridHighlightConfig
this.highlightConfig.GridHighlightConfig[Param] := Json.true
else
MsgBox 0x40010, , % "<" Param "> is wrong parameter"
}
; highlight element and parameters what should be visible while highlight
highlight(Info:=0,Styles:=0,Rulers:=0,AccInfo:=0,SaveConfig:=0)
{
;highlightConfig["contrastAlgorithm"] := "apca"
if !this.highlightConfig
{
MsgBox 0x40030, , Please Set Highlight Configuration`nusing Element.highlightConfigurations()
return
}
if Info
this.highlightConfig["showInfo"] := json.true
if Styles
this.highlightConfig["showStyles"] := json.true
if Rulers
this.highlightConfig["showRulers"] := json.true
if AccInfo
this.highlightConfig["showAccessibilityInfo"] := json.true
this.call("Overlay.enable")
x := this.call("Overlay.highlightNode",{"highlightConfig":this.highlightConfig,"nodeId":this.nodeId})
tooltip % json.Dump(x)
if(SaveConfig = 0)
this.highlightConfig := ""
return this.highlightConfig
}
OuterHTML ; extract outerhtml on request
{
get
{
return this.call("DOM.getOuterHTML",{"nodeId":this.nodeId}).OuterHTML
}
set
{
this.call("DOM.setOuterHTML",{"nodeId":this.nodeId,"outerHTML":value})
}
}
getAttributes()
{
for k, v in this.call("DOM.getAttributes",{"nodeId":this.nodeId}).attributes
{
if( mod(a_index, 2) != 1)
{
this[key] := v
}
key := V
}
}
; attrib should be case sensative i.e. class, value and or any custom attrib
getAttribute(attrib)
{
for k, v in this.call("DOM.getAttributes",{"nodeId":this.nodeId}).attributes
{
if( mod(a_index, 2) != 1)
{
if(Key = attrib)
return v
}
key := V
}
}
setAttribute(Name,Value)
{
this.call("DOM.setAttributeValue",{"nodeId":this.nodeId,"name":Name,"value":Value}).NodeID
this[Name] := this.getAttribute(Name)
return Value
}
;;;;;;;;;;;; events
; Str is string
; type Allowed Values: keyDown, keyUp, rawKeyDown but...
; for text parameter is KeyDownRaw and KeyUp are not required
; in simple type KeyDownRaw and KeyUp are forbidden
SendKey(str,type:="keyDown")
{
this.focus()
for k, v in StrSplit(str)
{
this.call("Input.dispatchKeyEvent",{"type":type,"text":v})
}
}
click(relativeX := 10,relativeY := 10)
{
Model := this.getBoxModel()
height := Model.height
width := Model.width
; An array of quad vertices, x immediately followed by y for each point, points clock-wise.
content := Model.content ; getting content quad
toprightx := content[1]
toprighty := content[2]
x := round(toprightx + (width / 2),0)
y := round(toprighty + ( height / 2),0)
this.ClickCoord(x,y, delay:= 10)
}
; x and y are coords
; Delay is delay between button down and button up
ClickCoord(x,y, delay:= 10)
{
MouseEvent := {"type":"mousePressed","button":"left","x":x,"y":y,"clickCount":1}
this.call("Input.dispatchMouseEvent",MouseEvent)
sleep, % delay
MouseEvent := {"type":"mouseReleased","button":"left","x":x,"y":y,"clickCount":1}
this.call("Input.dispatchMouseEvent",MouseEvent)
}
}
Class CDPElement extends CDP
{
__new(nodeId,address)
{
this.address := address
Node := this.call("DOM.describeNode",{"nodeId":nodeId}).node
this.nodeId := nodeId
this.Name := node.nodeName
this.localName := node.localName
this.parentId := node.parentId
this.backendNodeId := node.backendNodeId
this.nodeType := node.nodeType
}
Value
{
set
{
this.call("DOM.setAttributeValue",{"nodeId":this.nodeId,"name":"value","value":Value})
return value
}
get
{
return this.getAttribute("Value")
}
}
Class
{
set
{
this.call("DOM.setAttributeValue",{"nodeId":this.nodeId,"name":"Class","value":Value})
return value
}
get
{
return this.getAttribute("Class")
}
}
id
{
set
{
this.call("DOM.setAttributeValue",{"nodeId":this.nodeId,"name":"id","value":Value})
return value
}
get
{
return this.getAttribute("id")
}
}
innerText
{
get
{
d := ComObjCreate("htmlfile")
d.write(this.outerHTML)
return d.querySelector("*").innerText
}
set
{
d := ComObjCreate("htmlfile")
d.write(ohtml := this.outerHTML)
iText := d.querySelector("*").innerText
nHtml := StrReplace(ohtml,itext,value)
if(ohtml != nHtml)
this.outerHTML := nHtml
return value
}
}
textContent
{
get
{
d := ComObjCreate("htmlfile")
d.write(this.outerHTML)
return d.querySelector("*").textContent
}
set
{
}
}
}
Class CDPPrintOptions ; https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
{
static A4_Default =
( LTrim Join
{
"landscape": json.false,
"printBackground": json.true,
"scale": 1,
"paperWidth": 50,
"paperHeight": 60,
"marginTop": 2,
"marginBottom": 2,
"marginLeft": 2,
"marginRight": 2
}
)
}