-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1455 lines (1270 loc) · 61.6 KB
/
Copy pathcontent.js
File metadata and controls
1455 lines (1270 loc) · 61.6 KB
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
/**
* 智能表单数据模拟助手 - 内容脚本
* 负责悬浮窗UI和页面表单填充逻辑
*/
// 确保SettingsManager已正确加载的安全检查
(function ensureSettingsManager() {
// 如果SettingsManager未加载,尝试重新加载
if (typeof globalThis.settingsManager === 'undefined' || globalThis.settingsManager === null) {
console.warn('SettingsManager未正确加载,尝试重新初始化...');
// 检查SettingsManager类是否已加载(注意:在content script中,类可能不会直接暴露给globalThis)
// 由于manifest.json中settingsManager.js在content.js之前加载,所以应该已经可用
try {
if (typeof SettingsManager !== 'undefined') {
globalThis.settingsManager = new SettingsManager();
// console.log('SettingsManager已重新初始化');
// 添加设置变化监听器
globalThis.settingsManager.notifySettingsChanged = function() {
// console.log('设置已更新,重新初始化数据生成器...');
const generator = globalThis.settingsManager.getDataGenerator();
// console.log('当前数据生成器:',
// generator === globalThis.mockDataGenerator ? '基础模式' :
// generator === globalThis.advancedMockDataGenerator ? '高级模式' : '未知');
};
} else {
console.warn('SettingsManager类未定义,等待manifest.json的正常加载顺序');
}
} catch (error) {
console.warn('SettingsManager初始化失败,等待正常加载:', error);
}
}
})();
class FloatingWidget {
constructor() {
this.widget = null;
this.isDragging = false;
this.dragOffset = { x: 0, y: 0 };
this.currentData = null;
this.init();
}
/**
* 初始化悬浮窗
*/
init() {
// 创建悬浮窗容器
this.widget = document.createElement('div');
this.widget.id = 'smart-form-filler-widget';
this.widget.innerHTML = this.getWidgetHTML();
// 应用样式
Object.assign(this.widget.style, {
position: 'fixed',
top: '20px',
right: '20px',
zIndex: '10000',
backgroundColor: 'rgba(255, 255, 255, 0.95)',
border: '1px solid #ddd',
borderRadius: '8px',
padding: '10px',
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
minWidth: '120px',
fontFamily: 'Arial, sans-serif',
fontSize: '12px',
backdropFilter: 'blur(10px)',
transition: 'all 0.3s ease'
});
// 添加到页面
document.body.appendChild(this.widget);
// 绑定事件
this.bindEvents();
// console.log('智能表单数据模拟助手悬浮窗已加载');
}
/**
* 获取悬浮窗HTML结构
*/
getWidgetHTML() {
return `
<div style="margin-bottom: 8px; font-weight: bold; color: #333; text-align: center;">
智能填充
</div>
<div style="font-size: 10px; color: #666; text-align: center; margin-bottom: 8px;">
当前模式: <span id="current-mode-display">检测中...</span>
</div>
<div style="display: flex; gap: 8px; flex-direction: column;">
<button id="refill-btn" style="
padding: 6px 12px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 11px;
transition: background 0.3s;
">重新填充</button>
<button id="repeat-btn" style="
padding: 6px 12px;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 11px;
transition: background 0.3s;
">重复填充</button>
</div>
<div style="
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #eee;
font-size: 10px;
color: #666;
text-align: center;
">
拖拽移动
</div>
`;
}
/**
* 更新模式显示
*/
updateModeDisplay() {
const modeDisplay = this.widget.querySelector('#current-mode-display');
if (modeDisplay && globalThis.settingsManager) {
const mode = globalThis.settingsManager.settings.dataMode || 'basic';
const modeText = mode === 'basic' ? '简单模式' : '高级模式';
const modeColor = mode === 'basic' ? '#007bff' : '#28a745';
modeDisplay.textContent = modeText;
modeDisplay.style.color = modeColor;
modeDisplay.style.fontWeight = 'bold';
}
}
/**
* 绑定悬浮窗事件
*/
bindEvents() {
const refillBtn = this.widget.querySelector('#refill-btn');
const repeatBtn = this.widget.querySelector('#repeat-btn');
// 重新填充按钮事件
refillBtn.addEventListener('click', () => {
this.refillAllForms();
});
// 重复填充按钮事件
repeatBtn.addEventListener('click', () => {
this.repeatFill();
});
// 鼠标悬停效果
refillBtn.addEventListener('mouseenter', () => {
refillBtn.style.background = '#45a049';
});
refillBtn.addEventListener('mouseleave', () => {
refillBtn.style.background = '#4CAF50';
});
repeatBtn.addEventListener('mouseenter', () => {
repeatBtn.style.background = '#1976D2';
});
repeatBtn.addEventListener('mouseleave', () => {
repeatBtn.style.background = '#2196F3';
});
// 拖拽功能
this.enableDragging();
// 初始更新模式显示
this.updateModeDisplay();
}
/**
* 启用拖拽功能
*/
enableDragging() {
this.widget.addEventListener('mousedown', (e) => {
if (e.target.tagName === 'BUTTON') return; // 按钮不触发拖拽
this.isDragging = true;
this.dragOffset.x = e.clientX - this.widget.offsetLeft;
this.dragOffset.y = e.clientY - this.widget.offsetTop;
document.addEventListener('mousemove', this.onMouseMove.bind(this));
document.addEventListener('mouseup', this.onMouseUp.bind(this));
this.widget.style.cursor = 'grabbing';
this.widget.style.opacity = '0.8';
});
}
onMouseMove(e) {
if (!this.isDragging) return;
this.widget.style.left = (e.clientX - this.dragOffset.x) + 'px';
this.widget.style.top = (e.clientY - this.dragOffset.y) + 'px';
this.widget.style.right = 'auto';
}
onMouseUp() {
this.isDragging = false;
document.removeEventListener('mousemove', this.onMouseMove.bind(this));
document.removeEventListener('mouseup', this.onMouseUp.bind(this));
this.widget.style.cursor = 'grab';
this.widget.style.opacity = '1';
}
/**
* 检查是否有显示的dialog
*/
hasVisibleDialog() {
// 查找主流前端框架的dialog选择器
const frameworkDialogs = document.querySelectorAll(`
/* Quasar */ .q-dialog__inner:not(.q-dialog__inner--minimized),
/* Element UI */ .el-dialog__wrapper:not([style*="display: none"]),
/* Ant Design */ .ant-modal-root .ant-modal-wrap:not([style*="display: none"]),
/* Bootstrap */ .modal.show, .modal.fade.show,
/* LayUI */ .layui-layer:not([style*="display: none"]),
/* Vuetify */ .v-dialog__container:not([style*="display: none"]),
/* Material-UI */ .MuiModal-root:not([style*="display: none"]),
/* PrimeVue */ .p-dialog-mask:not([style*="display: none"]),
/* iView */ .ivu-modal-wrap:not([style*="display: none"]),
/* Native HTML */ dialog[open],
/* Generic */ .dialog:not([style*="display: none"]), .modal:not([style*="display: none"]),
/* Baidu Login */ .tang-pass-pop-login, .passport-login-pop, .tang-pass-pop-login-merge, .passport-login-container
`);
const visibleDialogs = Array.from(frameworkDialogs).filter(dialog => {
const style = window.getComputedStyle(dialog);
// 1. 基础样式检查
if (style.display === 'none' || style.visibility === 'hidden') {
return false;
}
// dialog.offsetParent !== null; element会返回null
// 2. 替代 offsetParent !== null:检查元素是否有实际的物理尺寸
// 只要宽高都大于 0,说明它一定在屏幕上占位渲染了
const rect = dialog.getBoundingClientRect();
const hasSize = rect.width > 0 && rect.height > 0;
return hasSize;
});
return visibleDialogs.length > 0;
}
/**
* 获取dialog内的表单元素
*/
getDialogFormElements() {
const dialogElements = [];
// 查找所有主流前端框架的dialog
const allDialogs = document.querySelectorAll(`
/* Quasar */ .q-dialog__inner:not(.q-dialog__inner--minimized),
/* Element UI */ .el-dialog__wrapper:not([style*="display: none"]),
/* Ant Design */ .ant-modal-root .ant-modal-wrap:not([style*="display: none"]),
/* Bootstrap */ .modal.show, .modal.fade.show,
/* LayUI */ .layui-layer:not([style*="display: none"]),
/* Vuetify */ .v-dialog__container:not([style*="display: none"]),
/* Material-UI */ .MuiModal-root:not([style*="display: none"]),
/* PrimeVue */ .p-dialog-mask:not([style*="display: none"]),
/* iView */ .ivu-modal-wrap:not([style*="display: none"]),
/* Native HTML */ dialog[open],
/* Generic */ .dialog:not([style*="display: none"]), .modal:not([style*="display: none"]),
/* Baidu Login */ .tang-pass-pop-login, .passport-login-pop, .tang-pass-pop-login-merge, .passport-login-container
`);
allDialogs.forEach(dialog => {
// 检查dialog是否可见
if (!this.isElementVisible(dialog)) {
return;
}
// 获取dialog内的表单元素
const inputs = dialog.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="file"])');
const textareas = dialog.querySelectorAll('textarea');
const selects = dialog.querySelectorAll('select');
const allElements = [...inputs, ...textareas, ...selects];
const mode = globalThis.settingsManager.getDataGenerator();
// console.log('当前模式:', mode);
allElements.forEach((element, index) => {
if (this.isElementVisible(element)) {
const type = mode.detectInputType(element);
dialogElements.push({
element: element,
type: type,
originalValue: element.value,
index: index,
isDialogElement: true,
dialogType: dialog.className || dialog.tagName
});
}
});
});
// console.log('dialog内的表单元素数量:', dialogElements.length, 'dialog类型:', dialogElements.map(el => el.dialogType));
return dialogElements;
}
/**
* 检查元素是否可见
*/
isElementVisible(element) {
if (!element) {
return false;
}
const style = window.getComputedStyle(element);
// 1. 基础样式检查
if (style.display === 'none' || style.visibility === 'hidden') {
return false;
}
// element.offsetParent !== null; element会返回null
// 2. 替代 offsetParent !== null:检查元素是否有实际的物理尺寸
// 只要宽高都大于 0,说明它一定在屏幕上占位渲染了
const rect = element.getBoundingClientRect();
const hasSize = rect.width > 0 && rect.height > 0;
return hasSize;
}
/**
* 检查当前是否在iframe中
*/
isInIframe() {
return window !== window.top;
}
/**
* 获取页面中的所有iframe
*/
getAllIframes() {
return document.querySelectorAll('iframe');
}
/**
* 向iframe发送填充数据
*/
sendDataToIframe(iframe, data) {
try {
iframe.contentWindow.postMessage({
type: 'SMART_FORM_FILL',
action: 'FILL_ALL_FORMS',
data: data,
source: 'smart-form-filler'
}, '*');
// console.log('向iframe发送数据:', iframe.src, data);
return true;
} catch (error) {
console.error('向iframe发送数据失败:', error);
return false;
}
}
/**
* 扫描页面所有表单元素(支持iframe)
*/
scanFormElements() {
const formElements = [];
// 优先检查是否有显示的dialog
if (this.hasVisibleDialog()) {
// console.log('检测到显示的dialog,严格只处理dialog内的表单元素');
const dialogElements = this.getDialogFormElements();
// 不再跳过iframe内的元素,因为现在支持iframe通信
// console.log('dialog内的表单元素数量:', dialogElements.length);
return dialogElements;
}
// 场景2:如果没有显示的dialog,检查是否在iframe中
if (this.isInIframe()) {
// console.log('在iframe中,扫描iframe内的表单元素');
const inputs = document.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="file"])');
const textareas = document.querySelectorAll('textarea');
const selects = document.querySelectorAll('select');
// 合并所有元素
const allElements = [...inputs, ...textareas, ...selects];
// console.log('iframe内扫描到的表单元素数量:', allElements.length);
const mode = globalThis.settingsManager.getDataGenerator();
// console.log('当前模式:', mode);
allElements.forEach((element, index) => {
if (this.isElementVisible(element)) {
// console.log(`处理iframe内第${index}个元素:`, {
// id: element.id,
// name: element.name,
// type: element.type,
// placeholder: element.placeholder,
// visible: this.isElementVisible(element)
// });
const type = mode.detectInputType(element);
formElements.push({
element: element,
type: type,
originalValue: element.value,
index: index,
isDialogElement: false,
inIframe: true
});
}
});
} else {
// 场景1:在主窗口且没有dialog,扫描整个页面的表单元素
// console.log('在主窗口且没有dialog,扫描整个页面的表单元素');
const inputs = document.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="file"])');
const textareas = document.querySelectorAll('textarea');
const selects = document.querySelectorAll('select');
// 合并所有元素
const allElements = [...inputs, ...textareas, ...selects];
// console.log('扫描到的表单元素数量:', allElements.length);
const mode = globalThis.settingsManager.getDataGenerator();
// console.log('当前模式:', mode);
allElements.forEach((element, index) => {
// 不再跳过iframe内的元素
if (this.isElementVisible(element)) {
// console.log(`处理第${index}个元素:`, {
// id: element.id,
// name: element.name,
// type: element.type,
// placeholder: element.placeholder,
// visible: this.isElementVisible(element),
// inIframe: element.closest('iframe') !== null
// });
const type = mode.detectInputType(element);
formElements.push({
element: element,
type: type,
originalValue: element.value,
index: index,
isDialogElement: false,
inIframe: element.closest('iframe') !== null
});
}
});
}
// console.log('最终识别的表单元素:', formElements.map(item => ({
// id: item.element.id,
// type: item.type,
// elementType: item.element.type,
// isDialogElement: item.isDialogElement,
// inIframe: item.inIframe
// })));
return formElements;
}
getActiveFormElements(formElements) {
var activeFormElements = [];
var selectElements = [];
for (let i = 0; i < formElements.length; i++) {
const item = formElements[i];
const element = item?.element; // 拿到真正的 DOM 元素
if(item.type == 'select'){
selectElements.push(item);
}
else if(this.isVivibleElement(item?.element)){
activeFormElements.push(item);
}
}
// console.log(activeFormElements)
return {
activeFormElements: activeFormElements,
selectElements: selectElements
};
}
isVivibleElement(element){
// 安全检查:如果该项没有 element,或者不是真正的 DOM,直接过滤掉
if (!element || typeof element.hasAttribute !== 'function') {
return false;
}
const tagName = element.tagName;
// 1. 处理标准表单元素
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(tagName)) {
// 特别注意:select 元素原生没有 readOnly 属性,只有 disabled
const isReadOnly = element.readOnly === true;
const isDisabled = element.disabled === true;
return !isReadOnly && !isDisabled;
}
// 2. 处理现代富文本/自定义输入框 (如 <div contenteditable="true">)
const isEditable = element.hasAttribute('contenteditable') &&
element.getAttribute('contenteditable') !== 'false';
if (isEditable) {
// 自定义组件通常通过类名(如 .is-disabled)或 aria 属性来标记禁用
const isCustomDisabled = element.classList.contains('disabled') ||
element.classList.contains('is-disabled') ||
element.getAttribute('aria-disabled') === 'true';
return !isCustomDisabled;
}
// 3. 既不是标准输入框也不是可编辑元素,直接过滤掉
return false;
}
isPage(element){
// 1. 获取输入框的提示词和当前值
const placeholderText = element.placeholder || '';
const currentValue = element.value || '';
// 2. 获取当前输入框外层包裹容器的文本(用来抓取“每页显示”或“条/页”这种旁边的文字)
const parentText = element.parentElement?.textContent || '';
// 🚨 核心过滤:如果包含分页特征字眼,直接忽略
const isPaginationText =
placeholderText.includes('条/页') ||
placeholderText.toLowerCase().includes('page') ||
currentValue.includes('条/页') ||
parentText.includes('条/页') ||
parentText.includes('每页');
return isPaginationText;
}
/**
* 自动处理 Element UI 下拉选择框的函数(支持单选、多选、自动收起)
* @param {Object} item 你的 formElements 数组中的单项对象
* @returns {Promise<void>}
*/
handleSelectElement(item) {
if (!item?.element || (item.element.readOnly && item.element.classList.contains('el-input__inner') == false) || item.element.disabled) return;
// 1. 防重锁:防止外部方法并发重复调用
if (item.element._isProcessing) return;
const input = item?.element;
const style = window.getComputedStyle(input);
var isVisible = style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0' &&
input.offsetHeight > 0;
if (!isVisible || this.isPage(input)) return;
if (!input || typeof input.hasAttribute !== 'function') return;
// 上锁,进入处理流程
item.element._isProcessing = true;
// 打开下拉菜单
input.click();
setTimeout(() => {
// 2. 获取当前层级最高、最新弹出的可见菜单
const visibleDropdowns = Array.from(document.querySelectorAll(
'.el-select-dropdown, .ant-select-dropdown, .arco-select-dropdown, [class*="select-dropdown"], [class*="select-menu"], [class*="dropdown-menu"]'
)).filter(el => {
const style = window.getComputedStyle(el);
return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0' && el.offsetHeight > 0;
});
var dropdownMenu = visibleDropdowns.sort((a, b) => {
const zA = parseInt(window.getComputedStyle(a).zIndex) || 0;
const zB = parseInt(window.getComputedStyle(b).zIndex) || 0;
return zA - zB;
})[visibleDropdowns.length - 1];
if (!dropdownMenu) {
const dropdownId = input.getAttribute('aria-controls') || input.getAttribute('aria-owns');
if (dropdownId) dropdownMenu = document.getElementById(dropdownId);
}
if (!dropdownMenu) {
item.element._isProcessing = false; // 未找到菜单提前解锁
return;
}
// 3. 跨框架识别多选模式
const isMultiple = dropdownMenu.classList.contains('is-multiple') ||
dropdownMenu.classList.contains('ant-select-dropdown-multiple') ||
dropdownMenu.classList.contains('arco-select-dropdown-multiple') ||
dropdownMenu.querySelector('.el-icon-check, .anticon-check, [class*="icon-check"], [class*="-check"]') !== null;
// 4. 获取所有可点击选项(严格过滤幽灵节点,确保元素真正有高宽)
const options = Array.from(dropdownMenu.querySelectorAll(
'.el-select-dropdown__item:not(.is-disabled), ' +
'.ant-select-item-option:not(.ant-select-item-option-disabled), ' +
'.arco-select-option:not([class*="disabled"]), ' +
'[class*="select-item-option"]:not([class*="disabled"]), ' +
'[class*="__item"]:not([class*="disabled"])'
)).filter(opt => opt.offsetHeight > 0 && opt.offsetWidth > 0); // 【跨框架核心过滤】:排除不可见或尺寸为0的重叠子节点
if (options.length === 0) {
document.body.click();
item.element._isProcessing = false;
return;
}
let totalWaitTime = 0;
if (isMultiple) {
const maxSelectable = Math.min(options.length, 3);
const selectCount = Math.floor(Math.random() * maxSelectable) + 1;
const shuffled = [...options].sort(() => 0.5 - Math.random());
const selectedOptions = shuffled.slice(0, selectCount);
// 多选递增延迟
selectedOptions.forEach((opt, i) => {
setTimeout(() => {
opt.click();
}, i * 150);
});
totalWaitTime = selectCount * 150;
} else {
// 5. 【单选防重机制】:严格随机选一个,并通过时间戳彻底断绝任何冒泡带来的二次点击
const randomIndex = Math.floor(Math.random() * options.length);
const targetOption = options[randomIndex];
const now = Date.now();
// 如果这个 DOM 节点或其父节点在 200ms 内被点过,直接拦截
if (!targetOption._lastClickedTime || (now - targetOption._lastClickedTime > 200)) {
targetOption._lastClickedTime = now;
targetOption.click();
}
totalWaitTime = 50;
}
// 6. 统一收起与完全解锁
setTimeout(() => {
const menuStyle = window.getComputedStyle(dropdownMenu);
const isMenuStillVisible = menuStyle.display !== 'none' &&
menuStyle.visibility !== 'hidden' &&
dropdownMenu.offsetHeight > 0;
if (isMenuStillVisible) {
document.body.click();
}
// 给 UI 框架留出充足的内部状态渲染时间,随后解锁
setTimeout(() => {
item.element._isProcessing = false;
}, 300);
}, totalWaitTime + 100);
}, 300);
}
/**
* 重新填充所有表单(支持iframe)
*/
async refillAllForms() {
const elementDic = this.getActiveFormElements(this.scanFormElements());
const formElements = elementDic.activeFormElements;
const selectElements = elementDic.selectElements;
const fillData = [];
// console.log(`扫描到 ${formElements.length} 个表单元素,开始智能填充...`);
// 分离iframe内外的元素
const mainWindowElements = formElements.filter(item => !item.inIframe);
const iframeElements = formElements.filter(item => item.inIframe);
// console.log(`主窗口元素: ${mainWindowElements.length}, iframe元素: ${iframeElements.length}`);
// 准备主窗口填充数据
mainWindowElements.forEach(item => {
const mockData = globalThis.settingsManager.getDataGenerator().generateMockData(item.type);
// console.log(`主窗口元素 ${item.index} (${item.element.id}) 类型: ${item.type}, 生成数据:`, mockData);
fillData.push({
type: item.type,
value: mockData,
elementInfo: {
id: item.element.id,
name: item.element.name,
placeholder: item.element.placeholder
},
inIframe: false
});
});
// 准备iframe填充数据
iframeElements.forEach(item => {
const mockData = globalThis.settingsManager.getDataGenerator().generateMockData(item.type);
// console.log(`iframe元素 ${item.index} (${item.element.id}) 类型: ${item.type}, 生成数据:`, mockData);
fillData.push({
type: item.type,
value: mockData,
elementInfo: {
id: item.element.id,
name: item.element.name,
placeholder: item.element.placeholder
},
inIframe: true,
iframeSrc: item.element.closest('iframe').src
});
});
// todo:判断iframe是否可见
// 处理下拉选择框
var time = 1;
for (let i = 0; i < selectElements.length; i++) {
const element = selectElements[i];
setTimeout(() => {
this.handleSelectElement(element);
}, time * 500);
time++;
}
// console.log('填充数据准备完成:', fillData);
// 执行主窗口批量填充
const mainResults = await globalThis.settingsManager.fillFormElements(mainWindowElements, fillData.filter(d => !d.inIframe));
// 处理iframe填充
const iframeResults = [];
if (iframeElements.length > 0 && !this.isInIframe()) {
// 只在主窗口中向iframe发送数据
const iframes = this.getAllIframes();
// console.log(`发现 ${iframes.length} 个iframe,开始发送填充数据`);
for (const iframe of iframes) {
const iframeData = fillData.filter(d => d.inIframe && d.iframeSrc === iframe.src);
if (iframeData.length > 0) {
const success = this.sendDataToIframe(iframe, iframeData);
iframeResults.push({
success: success,
iframeSrc: iframe.src,
elementCount: iframeData.length,
message: success ? '数据已发送到iframe' : '发送失败'
});
}
}
}
// 保存填充数据到session storage,建立索引映射
const indexedData = {};
formElements.forEach((item, index) => {
if (fillData[index]) {
indexedData[item.index] = fillData[index];
}
});
this.currentData = indexedData;
sessionStorage.setItem('smartFormFillData', JSON.stringify(indexedData));
const totalSuccess = mainResults.filter(r => r.success).length + iframeResults.filter(r => r.success).length;
this.showNotification(`成功填充了 ${totalSuccess} 个表单元素(主窗口:${mainResults.filter(r => r.success).length}, iframe:${iframeResults.filter(r => r.success).length})`);
return [...mainResults, ...iframeResults];
}
/**
* 重复填充(使用上次的数据)
*/
async repeatFill() {
if (!this.currentData) {
// 尝试从session storage恢复数据
const storedData = sessionStorage.getItem('smartFormFillData');
if (storedData) {
this.currentData = JSON.parse(storedData);
// console.log('从sessionStorage恢复的数据:', this.currentData);
} else {
this.showNotification('没有找到之前的填充数据,请先点击"重新填充"');
return [];
}
}
const formElements = this.scanFormElements();
const fillData = [];
// console.log('重复填充:扫描到的表单元素数量:', formElements.length);
// console.log('重复填充:保存的数据:', this.currentData);
formElements.forEach(item => {
// 尝试通过索引匹配数据
if (this.currentData[item.index]) {
fillData.push({
type: this.currentData[item.index].type,
value: this.currentData[item.index].value,
elementInfo: this.currentData[item.index].elementInfo
});
} else {
// 如果索引不匹配,尝试通过元素信息匹配(更灵活的匹配逻辑)
const matchedData = Object.values(this.currentData).find(data => {
if (!data.elementInfo) return false;
// 优先匹配id和name都相同的情况
if (data.elementInfo.id === item.element.id &&
data.elementInfo.name === item.element.name) {
return true;
}
// 如果id相同,name为空或相同
if (data.elementInfo.id === item.element.id &&
(!data.elementInfo.name || data.elementInfo.name === item.element.name)) {
return true;
}
// 如果name相同,id为空或相同
if (data.elementInfo.name === item.element.name &&
(!data.elementInfo.id || data.elementInfo.id === item.element.id)) {
return true;
}
// 如果placeholder相同
if (data.elementInfo.placeholder === item.element.placeholder &&
data.elementInfo.placeholder) {
return true;
}
return false;
});
if (matchedData) {
fillData.push({
type: matchedData.type,
value: matchedData.value,
elementInfo: matchedData.elementInfo
});
}
}
});
// console.log('重复填充数据:', fillData);
if (fillData.length === 0) {
this.showNotification('没有找到匹配的填充数据,请先点击"重新填充"');
return [];
}
const results = await globalThis.settingsManager.fillFormElements(formElements, fillData);
const successCount = results.filter(r => r.success).length;
if (successCount === 0) {
this.showNotification('重复填充失败,没有成功填充任何表单元素');
} else {
this.showNotification(`重复填充了 ${successCount} 个表单元素`);
}
return results;
}
/**
* 显示通知消息
*/
showNotification(message) {
// 创建临时通知元素
const notification = document.createElement('div');
notification.textContent = message;
Object.assign(notification.style, {
position: 'fixed',
top: '60px',
right: '20px',
zIndex: '10001',
backgroundColor: '#4CAF50',
color: 'white',
padding: '10px 16px',
borderRadius: '4px',
fontSize: '12px',
boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
transition: 'all 0.3s ease'
});
document.body.appendChild(notification);
// 3秒后自动消失
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateY(-10px)';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
/**
* 销毁悬浮窗
*/
destroy() {
if (this.widget && this.widget.parentNode) {
this.widget.parentNode.removeChild(this.widget);
}
}
}
// 监听来自主窗口的填充消息
window.addEventListener('message', (event) => {
// 安全检查:验证消息来源和类型
if (event.data &&
event.data.source === 'smart-form-filler' &&
event.data.type === 'SMART_FORM_FILL') {
// console.log('收到填充消息:', event.data);
switch (event.data.action) {
case 'FILL_ALL_FORMS':
// 处理批量填充
if (event.data.data && Array.isArray(event.data.data)) {
handleIframeFill(event.data.data);
}
break;
case 'FILL_SINGLE_FIELD':
// 处理单个字段填充
if (event.data.fieldData) {
handleSingleFieldFill(event.data.fieldData);
}
break;
}
}
});
/**
* 处理iframe内的表单填充
*/
async function handleIframeFill(fillData) {
// console.log('开始处理iframe填充数据:', fillData);
// 等待依赖加载完成
const waitForDependencies = () => {
if (typeof globalThis.mockDataGenerator !== 'undefined' &&
globalThis.mockDataGenerator !== null &&
typeof globalThis.mockDataGenerator.generateMockData === 'function' &&
typeof globalThis.settingsManager !== 'undefined' &&
globalThis.settingsManager !== null) {
// 扫描iframe内的表单元素
const floatingWidget = new FloatingWidget();
const formElements = floatingWidget.scanFormElements();
// console.log(`iframe内扫描到 ${formElements.length} 个表单元素`);
// 准备填充数据
const iframeFillData = [];
formElements.forEach((item, index) => {
if (index < fillData.length) {
iframeFillData.push({
type: fillData[index].type,
value: fillData[index].value,
elementInfo: fillData[index].elementInfo
});
}
});
// 执行填充
globalThis.settingsManager.fillFormElements(formElements, iframeFillData)
.then(results => {
// console.log('iframe填充完成:', results);
// 向主窗口发送完成通知
if (window.parent !== window) {
window.parent.postMessage({
type: 'SMART_FORM_FILL_RESPONSE',
action: 'FILL_COMPLETE',
source: 'smart-form-filler',
results: results,
iframeUrl: window.location.href
}, '*');
}
})
.catch(error => {
console.error('iframe填充失败:', error);
});
} else {
setTimeout(waitForDependencies, 100);
}
};
waitForDependencies();
}
/**
* 处理单个字段填充
*/
async function handleSingleFieldFill(fieldData) {
// console.log('处理单个字段填充:', fieldData);
// 等待依赖加载完成
const waitForDependencies = () => {
if (typeof globalThis.settingsManager !== 'undefined' && globalThis.settingsManager !== null) {
// 查找目标元素