forked from yangyuan02/chrome-Extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.js
1769 lines (1648 loc) · 76.9 KB
/
code.js
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
if (!window.uiaMetadata) {
window.uiaMetadata = {
uidKey: 'uia-uid',
latestUid: 0
}
}
const TAGS = {
BODY: 'BODY',
TABLE: 'TABLE',
INPUT: 'INPUT',
BUTTON: 'BUTTON',
SELECT: 'SELECT',
LABEL: 'LABEL',
TEXTAREA: 'TEXTAREA',
IFRAME: 'IFRAME',
FRAME: 'FRAME',
A: 'A',
IMG: 'IMG'
}
const CLICK_TYPE = {
CLICK: 0,
RIGHT_CLICK: 1,
DOUBLE_CLICK: 2,
MIDDLE_CLICK: 3,
HOVER: 4
}
// sync with enum KeyModifiers
const KEY_MODIFIERS = {
NONE: 0,
ALT: 1,
CTRL: 2,
SHIFT: 4
}
const CHECK_MODE = {
CHECK: 0,
UNCHECK: 1,
TOGGLE: 2
}
const MATCH_MODE = {
FUZZY: 0,
EXACT: 1,
REGEX: 2
}
const UIAERROR_CODE = {
ValidationFail: -2, // 参数验证失败
Unknown: -1, // 未知异常
Common: 1, // 通用异常
UIDriverConnectionError: 9, // UIDriver连接错误
CEFBrowserConnectionError: 10, // CEF浏览器连接错误
NonsupportOperation: 13, // 元素不支持此操作
NoSuchWindow: 100, // 未找到窗口
NoSuchElement: 101, // 未找到元素
NoSuchFrame: 102, // 未找到Frame
PageIsLoading: 103, // 网页尚未加载完成
FrameIsLoading: 104, // 网页中的Frame尚未加载完成
JavaScriptError: 105, // JavaScript执行出错
NoSuchElementID: 106, // 未找到元素指定的元素ID(缓存失效)
}
const SCROLL_BEHAVIOR = {
AUTO: 'auto',
SMOOTH: 'smooth'
}
const NBSP_REGEXP = new RegExp(String.fromCharCode(160), "g")
const domUtils = new function () {
this.matchElementType = (ele, ...tags) => {
if (!!ele && ele.nodeType === Node.ELEMENT_NODE) {
const curTag = domUtils.getTagName(ele).toUpperCase()
for (const tag of tags) {
if (tag === curTag) {
return true
}
}
}
return false
}
this.findAncestor = (ele, condition, includeSelf = true) => {
let cur = ele
while (cur) {
if (cur && (includeSelf || cur !== ele) && condition(cur) === true)
return cur
cur = cur.parentElement
}
return null
}
this.getSmoothScrollContainer = (ele) => {
let cur = ele.parentElement
do {
let inlineBehavior = cur.style.scrollBehavior //默认为 "" 除非scrolling box inline显示设置 scroll-behavior style
let computedBehavior = getComputedStyle(cur).scrollBehavior //默认为"auto" 除非在css样式中设置 scroll-behavior: smooth
let currentBehavior = inlineBehavior || computedBehavior
if (currentBehavior.toLowerCase() === SCROLL_BEHAVIOR.SMOOTH) {
return cur
} else {
cur = cur.parentElement
}
} while (cur && !domUtils.matchElementType(cur, TAGS.IFRAME, TAGS.FRAME))
return null
}
this.updateContainerScrollBehavior = (container, updateBehavior) => {
container.style.scrollBehavior = updateBehavior
}
//从dom element对象上获取eid属性,如果不存在就设置
this.uidFromElement = (element) => {
let uid = element.getAttribute(window.uiaMetadata.uidKey)
if (uid === null) {
window.uiaMetadata.latestUid += 1
uid = `${window.uiaDispatcher.frameBackendId}|${window.uiaMetadata.latestUid}` //fid|sequence
element.setAttribute(window.uiaMetadata.uidKey, uid)
}
return uid + ':' + domUtils.getTagName(element) //fid|sequence:tagType
}
//根据eid获取dom element对象
this.ElementFromUid = (uid) => {
const tokens = uid.split(':')
const element = document.querySelector(`${tokens[1]}[${window.uiaMetadata.uidKey}='${tokens[0]}']`) //tagType[uia-uid='fid|sequence']
if (!element) {
throw new UIAError(UIAERROR_CODE.NoSuchElementID, '未找到指定ID的元素')
}
return element
}
//获取子frame中父frame中的索引位置
this.getFrameIndex = (frame) => {
if (frame.parent === frame || frame.parent === null) {
return -1
} else {
const wnds = frame.parent.frames
for (let i = 0; i < wnds.length; i++) {
if (wnds[i] === frame) {
return i
}
}
return -1
}
}
//获取节点名称
this.getTagName = (element) => {
// 某些情况下Form标签的tagName是input元素
if (typeof (element.tagName) === 'string') {
return element.tagName.toLowerCase()
} else {
return element.nodeName.toLowerCase()
}
}
//子frame在父frame中的索引位置 -> 子frame在父frame中的DOM对象 (必须要先拿到frame的dom对象才能进行下一步的dom操作)
this.getFrameByIndex = (index) => { //子frame的索引位置
//1、先在父frame中找到所有的frame dom对象
const nodes = document.querySelectorAll('frame, iframe')
//2、找到和指定frame匹配的dom frame对象
for (const frame of nodes) {
if (frame.contentWindow === window.frames[index]) { //frame dom对象中的contentWindow才是frame对象
return frame
}
}
return null
}
// 获取DOM对象在当前frame中的路径
this.buildCSSPath = (element) => {
if (element.nodeType !== 1) {
return null
}
//计算元素的CSS路径
const path = []
do {
const tagName = domUtils.getTagName(element)
if (tagName === 'body' || tagName === 'html') {
// 防止path为空导致后续QuerySelecor报错
if (path.length == 0) {
path.unshift(tagName)
}
break
}
path.unshift(tagName)
element = element.parentNode
} while (element)
return this.cssPathEscape(path.join('>'))
}
this.extractAttributes = (element) => {
const attrDict = {}
const names = element.getAttributeNames()
for (const name of names) {
let value = element.getAttribute(name)
switch (name) {
case 'id':
attrDict['id'] = value
break
case 'title':
if (value.length < 50) {
attrDict['title'] = value
}
break
case 'class':
case 'style':
case window.uiaMetadata.uidKey:
break
default:
attrDict[name] = value
break
}
}
if (element.classList.length > 0) {
attrDict['class'] = [...element.classList].map(item => item.toLowerCase()).sort().join(' ')
}
if (element.childElementCount === 0 && //只有当DOM元素中没有子元素时才会取它的innerText
!domUtils.matchElementType(element, TAGS.INPUT, TAGS.SELECT, TAGS.TEXTAREA)) {
let text = element.innerText
if (text && text.length > 0 && text.length < 50) {
attrDict['innerText'] = text
}
}
if (element.parentElement) {
attrDict['index'] = Array.prototype.indexOf.call(element.parentElement.children, element).toString()
}
return attrDict
}
this.buildSelector = (element) => {
const path = []
const cssPath = this.buildCSSPath(element)
let others = document.querySelectorAll(cssPath)
let webNode = new WebNode(element)
do {
const nextOthers = []
for (const other of others) {
const otherWebNode = new WebNode(other)
if (!webNode.diff(otherWebNode)) {
nextOthers.push(other.parentNode)
}
}
path.unshift(webNode.toSelectorNode())
webNode = webNode.parent()
others = nextOthers
} while (webNode)
return path
}
//根据selector对象 -> 寻找元素 (用户录制的路径sPath可能会跨域)
this.querySPath = (sPath, parent = null, shift = true) => {
//判断两个属性值是否等价
function isAttributeMatch(value, sAttr) {
switch (sAttr.operator) {
case 'Equal':
if (sAttr.name === 'class') {
if (value === sAttr.value) {
return true
} else {
if (!value) {
return false
}
//"red h1" 等价于 "h1 red",忽略顺序
sValue = sAttr.value.match(/[^ ]+/g).map(item => item.toLowerCase()).sort().join(' ')
return value === sValue
}
} else {
return value === sAttr.value
};
case 'Regex': // 正则和通配符直接使用用户提供的表达式匹配
try {
return (new RegExp(sAttr.value)).test(value);
} catch (e) {
throw new ActionError(`不支持的正则表达式 : ${sAttr.value}`)
}
case 'WildCard':
return wildcardsMatchText(sAttr.value, value);
default:
return false
}
}
// index typeIndex不支持正则和通配符
function isIndexAttributeMatch(total, eleIndex, nodeIndex) {
if (parseInt(nodeIndex) < 0) {
var a = total == Math.abs(nodeIndex) + Math.abs(eleIndex)
return a
} else {
return nodeIndex === eleIndex
}
}
//链式判断:selector.node1 -> element,selector.node2 -> element.parent,selector.node3 -> element.parent.parent
function isElementMatchSelector(element, selector) {
const selectorLength = selector.length
let ele = element
for (let i = selectorLength - 1; i >= 0; i--) {
const node = selector[i]
if (node.attributes && node.attributes.length > 0) {
var attrs = domUtils.extractAttributes(ele)
for (const sAttr of node.attributes) { //选择器一个节点中的所有属性node.attributes,sAttr
if (sAttr.required) {
if (sAttr.name === "index") {
if (!isIndexAttributeMatch(ele.parentElement.children.length, attrs[sAttr.name], sAttr.value)) {
return false;
}
} else if (sAttr.name === "index-of-type") {
const tagName = domUtils.getTagName(ele)
const elements = Array.prototype.filter.call(ele.parentElement.children, e => domUtils.getTagName(e) === tagName);
const eleIndex = Array.prototype.indexOf.call(elements, ele).toString()
if (!isIndexAttributeMatch(elements.length, eleIndex, sAttr.value)) {
return false;
}
} else {
// <input> type属性默认为 "text", match时"text"等效于 undefined
if (domUtils.getTagName(ele) === "input" && sAttr.name === "type" && sAttr.value === "text") {
if (attrs[sAttr.name] && attrs[sAttr.name] !== "text") {
return false;
}
}
// 兼容已存在非leaf节点但有 innerText属性的 selector /or/ 最后一个selector节点(非 leaf节点) 用户手动添加了 innerText的情况
if (i === selectorLength - 1 && sAttr.name === "innerText" && ele.childElementCount) {
attrs["innerText"] = ele.innerText
}
if (!isAttributeMatch(attrs[sAttr.name], sAttr)) {
return false;
}
}
}
}
}
ele = ele.parentElement //...
}
return true
}
function wildcardsMatchText(wcValue, text) {
function wildcardToRegex(pattern) {
return '^' + pattern.replace('*', '.*').replace('?', '.') + '$'
}
const wcRegex = wildcardToRegex(wcValue)
return (new RegExp(wcRegex, 'im')).test(text);
}
//0、预处理 (如果路径跨域就返回在前一个域中的路径)
const root = parent || document
const sPathInFrame = []
if (shift) {
//如 sPath -> div>div>div>iframe>div>div>a,那么sPathInFrame -> div>div>div>iframe,shift模式下sPath -> div>div>a
while (sPath.length > 0) {
const sNode = sPath.shift()
sPathInFrame.push(sNode)
if (sNode.name === 'iframe' || sNode.name === 'frame') {
break
}
}
} else {
for (const sNode of sPath) {
sPathInFrame.push(sNode)
if (sNode.name === 'iframe' || sNode.name === 'frame') {
break
}
}
}
//1、节点级的初步匹配
const cssSelector = this.cssPathEscape(sPathInFrame.map(m => m.name).join('>')) // div>div>div>iframe
const elements = root.querySelectorAll(cssSelector) //用户路径跨域的情况下,会获取到iframe这个元素,即elements[0]
//2、属性级的详细过滤
const matchedElements = []
for (const element of elements) {
if (isElementMatchSelector(element, sPathInFrame)) {
matchedElements.push(element)
}
}
return matchedElements
}
//根据CSS路径字符串 -> 寻找元素
this.queryCSSPath = (cssPath, parent = null) => {
const root = parent || document
const cssResult = root.querySelectorAll(cssPath) //nodelist
return [...cssResult]
}
//根据XPath路径字符串 -> 寻找元素
this.queryXPath = (xPath, parent = null) => {
//console.log('xPath' + xPath)
//console.log('parent' + parent)
const root = parent || document
var xPathResult = document.evaluate(xPath, root, null, XPathResult.ANY_TYPE, null)
var elements = []
while (element = xPathResult.iterateNext()) {
elements.push(element)
}
return elements
}
this.raiseClickEvent = (clickType, element, x, y, keyModifiers) => {
let types = []
let button = 0
if (clickType === CLICK_TYPE.HOVER) {
types = ["mouseover", "mouseenter", "mousemove"]
button = 0
} else if (clickType === CLICK_TYPE.DOUBLE_CLICK) {
types = ["mousedown", "mouseup", "click", "mousedown", "mouseup", "click", "dblclick"]
button = 0
} else if (clickType === CLICK_TYPE.RIGHT_CLICK) {
types = ["mousedown", "mouseup", "contextmenu"]
button = 2
} else if (clickType === CLICK_TYPE.MIDDLE_CLICK) {
types = ["mousedown", "mouseup", "click"]
button = 1
} else {
types = ["mousedown", "mouseup", "click"]
button = 0
}
const ctrlKey = !!(keyModifiers & KEY_MODIFIERS.CTRL)
const altKey = !!(keyModifiers & KEY_MODIFIERS.ALT)
const shiftKey = !!(keyModifiers & KEY_MODIFIERS.SHIFT)
let waitTime = 0 //延时执行,保证event生效 尝试了时间递增1不可以
for (const type of types) {
waitTime += 50
setTimeout(() => {
var evt = document.createEvent("MouseEvents")
evt.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, ctrlKey, altKey, shiftKey, false, button, null)
element.dispatchEvent(evt)
}, waitTime)
}
}
this.raiseClickOnElement = (element) => {
const rect = element.getBoundingClientRect()
domUtils.raiseClickEvent(CLICK_TYPE.CLICK, element, rect.x + rect.width / 2, rect.y + rect.height / 2, KEY_MODIFIERS.NONE)
}
this.toString = (any) => {
return (any === null || any === undefined) ? null : any.toString()
}
this.matchText = (matchMode, matchValue, text) => {
if (matchMode === MATCH_MODE.EXACT) {
return matchValue === text
} else if (matchMode === MATCH_MODE.FUZZY) {
return text && text.indexOf(matchValue) > -1
} else { // MATCH_MODE.REGEX
return (new RegExp(matchValue)).test(text)
}
}
this.getFrameOffset = (element) => {
const pLeft = parseInt(window.getComputedStyle(element, null).getPropertyValue('padding-left')) || 0
const pTop = parseInt(window.getComputedStyle(element, null).getPropertyValue('padding-top')) || 0
const bLeft = parseInt(window.getComputedStyle(element, null).getPropertyValue('border-left-width')) || 0
const bTop = parseInt(window.getComputedStyle(element, null).getPropertyValue('border-top-width')) || 0
return {
x: pLeft + bLeft,
y: pTop + bTop
}
}
this.pointLikeScale = (pointLike, zoom) => {
return {
x: pointLike.x / zoom,
y: pointLike.y / zoom
}
}
this.cssPathEscape = (value) => {
if (!value) {
return null
}
var cssStr = String(value);
var length = cssStr.length;
var index = -1;
var codeUnit;
var result = '';
var firstCodeUnit = cssStr.charCodeAt(0);
while (++index < length) {
codeUnit = cssStr.charCodeAt(index);
//类型 1.图形一类的特殊字符
if (codeUnit < 0x20 || codeUnit > 0x7E) {
if (codeUnit >= 0xD800 && codeUnit <= 0xDBFF && index < length) {
// It’s a high surrogate, and there is a next character.
var extra = cssStr.charCodeAt(index++);
if ((extra & 0xFC00) == 0xDC00) {
// next character is low surrogate
codeUnit = ((codeUnit & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
} else {
// It’s an unmatched surrogate; only append this code unit, in case
// the next code unit is the high surrogate of a surrogate pair.
index--;
}
}
result += '\\' + codeUnit.toString(16).toUpperCase() + ' ';
continue;
} else {
// 类型 2.如果为 NULL (U+0000),使用(U+FFFD)替换
if (codeUnit == 0x0000) {
result += '\uFFFD';
continue;
}
// 类型 3.使用unicode
// [1-1F] (U+0001 to U+001F)
// U+007F, 0x003A […]
// 第一项为 [0-9] (U+0030 to U+0039), […]
// 第二项为 [0-9] (U+0030 to U+0039) 且第一项是 `-` (U+002D), […]
if ((codeUnit >= 0x0001 && codeUnit <= 0x001F) ||
codeUnit == 0x007F || codeUnit == 0x003A ||
(index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
(index == 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit == 0x002D)) {
result += '\\' + codeUnit.toString(16) + ' ';
continue;
}
// 类型 4.使用`\`转义
// 只有一项,且为 `-` (U+002D), […]
if (index == 0 && length == 1 && codeUnit == 0x002D) {
result += '\\' + cssStr.charAt(index);
continue;
}
// 类型 5.使用字符本身 不需要特殊处理
// `-` (U+002D) 或 `>` (0x003E) 或 `_` (U+005F),
// is in one of the ranges [0-9] (U+0030 to U+0039)
//[A-Z] (U+0041 to U+005A)
//[a-z] (U+0061 to U+007A), […]
if (codeUnit == 0x002D || codeUnit == 0x003E || codeUnit == 0x005F ||
codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
codeUnit >= 0x0041 && codeUnit <= 0x005A ||
codeUnit >= 0x0061 && codeUnit <= 0x007A) {
result += cssStr.charAt(index);
continue;
}
// 否则 没有检测到的字符 直接转义
result += '\\' + cssStr.charAt(index);
}
}
return result;
}
this.replaceNbspToSpace = (value) => {
if(value){
value = value.replace(NBSP_REGEXP, String.fromCharCode(32))
}
return value
}
// 获取当前元素有滚动条的父节点,到document为止,如果
this.getScrollableParent = (element, direction) => {
var ret = element;
if(direction == "vertical"){
while (ret) {
if (ret.scrollHeight <= ret.clientHeight) {
ret = ret.parentElement;
} else {
break;
}
}
}
else if(direction == "horizontal"){
while (ret) {
if (ret.scrollWidth <= ret.clientWidth) {
ret = ret.parentElement;
} else {
break;
}
}
}
if (!ret)
ret = element;
return ret;
}
}
class Bubbling {
constructor(args) {
this.args = args
}
}
class Tunneling {
constructor(frame, args) {
this.args = args
this.frameIndex = domUtils.getFrameIndex(frame.contentWindow)
}
}
class ActionError extends Error {
constructor(message) {
super(message || "")
}
}
class UIAError extends Error {
constructor(code, message) {
super(message || "")
this.code = code
}
}
class Rect {
constructor(x, y, width, height) {
this.x = x
this.y = y
this.width = width
this.height = height
}
contains(point) {
return point.x >= this.x && point.x <= (this.width + this.x) && point.y >= this.y && point.y <= (this.height + this.y)
}
center() {
return {
x: Math.round(this.x + this.width / 2),
y: Math.round(this.y + this.height / 2)
}
}
offset(x, y) {
this.x += x
this.y += y
}
scale(ratio) {
return new Rect(Math.round(this.x * ratio), Math.round(this.y * ratio),
Math.round(this.width * ratio), Math.round(this.height * ratio))
}
ScaleInv(ratio) {
return new Rect(Math.round(this.x / ratio), Math.round(this.y / ratio),
Math.round(this.width / ratio), Math.round(this.height / ratio))
}
intersect(rect) {
const x1 = Math.max(this.x, rect.x)
const x2 = Math.min(this.x + this.width, rect.x + rect.width)
const y1 = Math.max(this.y, rect.y)
const y2 = Math.min(this.y + this.height, rect.y + rect.height)
if (x2 >= x1 && y2 >= y1) {
return new Rect(x1, y1, x2 - x1, y2 - y1)
} else {
return null
}
}
static fromDOMRect(domRect) {
return new Rect(Math.round(domRect.x), Math.round(domRect.y),
Math.round(domRect.width), Math.round(domRect.height))
}
}
class WebNode {
constructor(element) {
this.element = element
this.classList = [...element.classList]
this.attributes = domUtils.extractAttributes(element)
this.required = new Set()
// 为了防止出现运行时经常匹配到多个的问题,这里多加入一些属性,尽量严格一点
if (domUtils.matchElementType(element, TAGS.INPUT, TAGS.BUTTON, TAGS.SELECT)) {
if (this.attributes['type']) {
this.required.add('type')
}
if (this.attributes['name']) {
this.required.add('name')
}
}
// 在diff的时候再判断是否required
// if (this.attributes['id'] && !(/\d+/.test(this.attributes['id']))) {
// this.required.add('id')
// }
}
attr(name) {
return this.attributes[name] || null
}
parent() {
const parent = this.element.parentElement
if (parent == null) { // 有可能录制的HTML节点
return null
}
const tagName = domUtils.getTagName(parent)
if (tagName === 'body' || tagName === 'html') {
return null
} else {
return new WebNode(parent)
}
}
diff(other) {
if (this.element === other.element) {
return true
}
const names = ['type', 'id', 'name', 'title', 'innerText', 'class', 'index']
for (const name of names) {
if (name === 'id' && /\d+/.test(this.attr(name))) {
continue
}
if (name === 'class') {
if (this.classList.length > 0) {
let classes = this.classList.filter(m => other.classList.indexOf(m) == -1);
if (classes.length > 0 && this.classList.some(m => !other.classList.includes(m)) && !/hover|[^a-zA-Z](?:on|open|active)/.test(classes.join(' '))) {
this.required.add(name)
return true
}
}
} else {
if (this.attr(name) !== null && this.attr(name) !== other.attr(name)) {
this.required.add(name)
return true
}
}
}
return false
}
toSelectorNode() {
const node = {
'name': domUtils.getTagName(this.element),
'type': 'Web',
'attributes': []
}
for (const [name, value] of Object.entries(this.attributes)) {
node.attributes.push({
'name': name,
'value': value,
'operator': 'Equal',
'required': this.required.has(name)
})
}
return node
}
}
window.uiaDispatcher = new function () {
const actions = {
getFrameIndex: (args) => {
return domUtils.getFrameIndex(window)
},
elementFromPoint: (args) => {
const element = document.elementFromPoint(args.x, args.y)
if (element) {
if (domUtils.matchElementType(element, TAGS.IFRAME, TAGS.FRAME)) {
const offset = domUtils.getFrameOffset(element)
const bounding = Rect.fromDOMRect(element.getBoundingClientRect())
return new Tunneling(element, {
x: args.x - bounding.x - offset.x,
y: args.y - bounding.y - offset.y
})
} else {
return domUtils.uidFromElement(element)
}
} else {
return null
}
},
inspectByPoint: (args) => {
if (!args.clientX)
args.clientX = 0
if (!args.clientY)
args.clientY = 0
if (!args.zoom) //内置浏览器是没有这个概念的 所以没有传zoom值
args.zoom = 1
const element = document.elementFromPoint(args.x, args.y)
if (element) {
const cssBounding = Rect.fromDOMRect(element.getBoundingClientRect())
if (domUtils.matchElementType(element, TAGS.IFRAME, TAGS.FRAME)) {
const offset = domUtils.pointLikeScale(domUtils.getFrameOffset(element), args.zoom)
return new Tunneling(element, {
//(x,y)->鼠标在subframe中的坐标
x: args.x - cssBounding.x - offset.x,
y: args.y - cssBounding.y - offset.y,
//(clientX,clientY)->鼠标在topfram中的坐标,越深值越大
clientX: args.clientX + cssBounding.x + offset.x,
clientY: args.clientY + cssBounding.y + offset.y,
zoom: args.zoom
})
} else {
if (args.clientX > 0 || args.clientY > 0) {
cssBounding.offset(args.clientX, args.clientY)
}
// 结果与InspectResult结构保持一致
const tagName = domUtils.getTagName(element).toUpperCase()
const finalBounding = cssBounding.scale(args.zoom)
return {
bounding: finalBounding,
info: ['INPUT', 'BUTTON'].includes(tagName) ?
tagName + ',' + element.getAttribute('type') : tagName
}
}
} else {
return null
}
},
selectorFromPoint: (args) => {
const element = document.elementFromPoint(args.x, args.y)
if (element) {
const sPath = domUtils.buildSelector(element)
if (domUtils.matchElementType(element, TAGS.IFRAME, TAGS.FRAME)) {
const bounding = Rect.fromDOMRect(element.getBoundingClientRect())
const offset = domUtils.getFrameOffset(element)
return new Tunneling(element, {
//(x,y)->鼠标在subframe中的坐标
x: args.x - bounding.x - offset.x,
y: args.y - bounding.y - offset.y,
sPath: args.sPath ? args.sPath.concat(sPath) : sPath
})
} else {
return args.sPath ? args.sPath.concat(sPath) : sPath
}
} else {
return null
}
},
//获取元素的全局路径(从mainframe开始)
pathFromMainFrameByElementId: (args) => {
var sPath = args.sPath || []
if (args.childFrameIndex !== undefined) { // request from child frame
const domFrame = domUtils.getFrameByIndex(args.childFrameIndex) //在父frame中的索引位置 -> 在父frame中的DOM对象
var frameSPath = domUtils.buildCSSPath(domFrame)
if (!frameSPath)
throw new ActionError('计算元素的全局路径时出错')
sPath = frameSPath.split(">").concat(sPath)
} else { // first request
const element = domUtils.ElementFromUid(args.elementId)
var elementSPath = domUtils.buildCSSPath(element)
if (!elementSPath)
throw new ActionError('计算元素的全局路径时出错')
sPath = elementSPath.split(">").concat(sPath)
}
const frameIndex = domUtils.getFrameIndex(window)
if (frameIndex === -1) { // top main frame
return sPath
} else {
return new Bubbling({
elementId: args.elementId,
sPath: sPath,
childFrameIndex: frameIndex
})
}
},
querySelectorAll: (args) => {
//1、预处理
const sPath = args.path
let parentElement = null
if (args.elementId) {
parentElement = domUtils.ElementFromUid(args.elementId)
}
//2、获取DOM对象列表
var elements = domUtils.querySPath(sPath, parentElement)
//3、同时处理用户录制的路径出现的(一般情况和跨域情况),跨域情况一般是指用户路径中包含iframe和frame元素
//3.1 用户路径跨域的情况下,elements只会包含一个iframe元素对象,elements[0]
if (elements.length === 1 &&
domUtils.matchElementType(elements[0], TAGS.IFRAME, TAGS.FRAME) &&
sPath.length > 0) {
return new Tunneling(elements[0], { //返回iframe对象及其路径,用于之后找到iframe在整个标签页browser中的索引位置
path: sPath //以shift模式调用querySPath时会修改sPath,此时sPath为在后一个域中的路径,如div>div>iframe>div>a,此时返回的sPath为div>a
})
}
//3.2 非跨域的情况下,直接返回普通元素对象的id即可
else {
return elements.map(m => domUtils.uidFromElement(m))
}
},
queryCSSSelectorAll: (args) => {
//1、预处理
const cssPath = args.path
let parentElement = null
if (args.elementId) {
parentElement = domUtils.ElementFromUid(args.elementId)
}
//2、获取DOM对象列表
var elements = domUtils.queryCSSPath(cssPath, parentElement)
//3、如果直接给一个跨域的CSS路径的话,不支持,目前仅模拟JS DOM操作的模式,忽略路径跨域的情况
/*
if (elements.length === 1 &&
domUtils.matchElementType(elements[0], TAGS.IFRAME, TAGS.FRAME) &&
sPath.length > 0) {
return new Tunneling(elements[0], {
path: cssPath
})
} else {
return elements.map(m => domUtils.uidFromElement(m))
}*/
return elements.map(m => domUtils.uidFromElement(m))
},
queryXPathSelectorAll: (args) => {
//1、预处理
const xPath = args.path
let parentElement = null
if (args.elementId) {
parentElement = domUtils.ElementFromUid(args.elementId)
}
//2、获取DOM对象列表
var elements = domUtils.queryXPath(xPath, parentElement)
//3、如果直接给一个跨域的XPath路径的话,不支持,目前仅模拟JS DOM操作的模式,忽略路径跨域的情况
/*
if (elements.length === 1 &&
domUtils.matchElementType(elements[0], TAGS.IFRAME, TAGS.FRAME) &&
sPath.length > 0) {
return new Tunneling(elements[0], {
path: xPath
})
} else {
return elements.map(m => domUtils.uidFromElement(m))
}*/
return elements.map(m => domUtils.uidFromElement(m))
},
//此方法似乎没用到
querySelector: (args) => {
const sPath = args.path
const elements = domUtils.querySPath(sPath)
if (elements.length === 0) {
throw new ActionError('找不到匹配的元素')
} else if (elements.length > 1) {
throw new ActionError('匹配到多个元素, 无法识别唯一属性')
} else {
if (domUtils.matchElementType(elements[0], TAGS.IFRAME, TAGS.FRAME) &&
sPath.length > 0) {
return new Tunneling(elements[0], {
path: sPath
})
} else {
return elements.map(m => domUtils.uidFromElement(m))
}
}
},
queryTableSelector: (args) => {
function getAttrValue(element, attrName, pattern) {
let result = null
if (attrName === 'Text') {
result = domUtils.replaceNbspToSpace(element.innerText || element.value || "")
} else if (attrName.includes('Href')) {
const eleA = domUtils.findAncestor(element, (e) => {
return domUtils.matchElementType(e, TAGS.A)
}, true)
if (eleA) {
result = attrName.includes('AbsoluteUrl') ? eleA.href : eleA.getAttribute('href')
} else {
result = null
}
} else if (attrName.includes('Image')) {
if (domUtils.matchElementType(element, TAGS.IMG)) {
result = attrName.includes('AbsoluteUrl') ? element.src : element.getAttribute('src')
} else {
result = null
}
} else {
result = null
}
if (pattern) {
const regex = new RegExp(pattern)
const arr = regex.exec(result)
if (arr) {
if (arr.length == 1) {
return arr[0] //整个匹配文本
} else {
return arr[1] //第1个子表达式相匹配的文本
}
} else {
return null
}
} else {
return result
}
}
//将列的查询结果限制在当前行中
function parentFromAnchor(anchor, generation) {
let parent = anchor
for (let i = 0; i < generation; i++) {