-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathcollect-autofill-content.service.ts
1431 lines (1257 loc) · 48.2 KB
/
collect-autofill-content.service.ts
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
import AutofillField from "../models/autofill-field";
import AutofillForm from "../models/autofill-form";
import AutofillPageDetails from "../models/autofill-page-details";
import { ElementWithOpId, FillableFormFieldElement, FormFieldElement } from "../types";
import {
elementIsDescriptionDetailsElement,
elementIsDescriptionTermElement,
elementIsFillableFormField,
elementIsFormElement,
elementIsInputElement,
elementIsLabelElement,
elementIsSelectElement,
elementIsSpanElement,
nodeIsElement,
elementIsTextAreaElement,
nodeIsFormElement,
nodeIsInputElement,
sendExtensionMessage,
getAttributeBoolean,
getPropertyOrAttribute,
requestIdleCallbackPolyfill,
cancelIdleCallbackPolyfill,
debounce,
} from "../utils";
import { AutofillOverlayContentService } from "./abstractions/autofill-overlay-content.service";
import {
AutofillFieldElements,
AutofillFormElements,
CollectAutofillContentService as CollectAutofillContentServiceInterface,
UpdateAutofillDataAttributeParams,
} from "./abstractions/collect-autofill-content.service";
import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service";
import { DomQueryService } from "./abstractions/dom-query.service";
export class CollectAutofillContentService implements CollectAutofillContentServiceInterface {
private readonly sendExtensionMessage = sendExtensionMessage;
private readonly getAttributeBoolean = getAttributeBoolean;
private readonly getPropertyOrAttribute = getPropertyOrAttribute;
private noFieldsFound = false;
private domRecentlyMutated = true;
private _autofillFormElements: AutofillFormElements = new Map();
private autofillFieldElements: AutofillFieldElements = new Map();
private currentLocationHref = "";
private intersectionObserver: IntersectionObserver;
private elementInitializingIntersectionObserver: Set<Element> = new Set();
private mutationObserver: MutationObserver;
private mutationsQueue: MutationRecord[][] = [];
private updateAfterMutationIdleCallback: NodeJS.Timeout | number;
private readonly updateAfterMutationTimeout = 1000;
private readonly formFieldQueryString;
private readonly nonInputFormFieldTags = new Set(["textarea", "select"]);
private readonly ignoredInputTypes = new Set([
"hidden",
"submit",
"reset",
"button",
"image",
"file",
]);
constructor(
private domElementVisibilityService: DomElementVisibilityService,
private domQueryService: DomQueryService,
private autofillOverlayContentService?: AutofillOverlayContentService,
) {
let inputQuery = "input:not([data-bwignore])";
for (const type of this.ignoredInputTypes) {
inputQuery += `:not([type="${type}"])`;
}
this.formFieldQueryString = `${inputQuery}, textarea:not([data-bwignore]), select:not([data-bwignore]), span[data-bwautofill]`;
}
get autofillFormElements(): AutofillFormElements {
return this._autofillFormElements;
}
/**
* Builds the data for all forms and fields found within the page DOM.
* Sets up a mutation observer to verify DOM changes and returns early
* with cached data if no changes are detected.
* @returns {Promise<AutofillPageDetails>}
* @public
*/
async getPageDetails(): Promise<AutofillPageDetails> {
if (!this.mutationObserver) {
this.setupMutationObserver();
}
if (!this.intersectionObserver) {
this.setupIntersectionObserver();
}
if (!this.domRecentlyMutated && this.noFieldsFound) {
return this.getFormattedPageDetails({}, []);
}
if (!this.domRecentlyMutated && this.autofillFieldElements.size) {
this.updateCachedAutofillFieldVisibility();
return this.getFormattedPageDetails(
this.getFormattedAutofillFormsData(),
this.getFormattedAutofillFieldsData(),
);
}
const { formElements, formFieldElements } = this.queryAutofillFormAndFieldElements();
const autofillFormsData: Record<string, AutofillForm> =
this.buildAutofillFormsData(formElements);
const autofillFieldsData: AutofillField[] = (
await this.buildAutofillFieldsData(formFieldElements as FormFieldElement[])
).filter((field) => !!field);
this.sortAutofillFieldElementsMap();
if (!autofillFieldsData.length) {
this.noFieldsFound = true;
}
this.domRecentlyMutated = false;
const pageDetails = this.getFormattedPageDetails(autofillFormsData, autofillFieldsData);
this.setupOverlayListeners(pageDetails);
return pageDetails;
}
/**
* Find an AutofillField element by its opid, will only return the first
* element if there are multiple elements with the same opid. If no
* element is found, null will be returned.
* @param {string} opid
* @returns {FormFieldElement | null}
*/
getAutofillFieldElementByOpid(opid: string): FormFieldElement | null {
const cachedFormFieldElements = Array.from(this.autofillFieldElements.keys());
const formFieldElements = cachedFormFieldElements?.length
? cachedFormFieldElements
: this.getAutofillFieldElements();
const fieldElementsWithOpid = formFieldElements.filter(
(fieldElement) => (fieldElement as ElementWithOpId<FormFieldElement>).opid === opid,
) as ElementWithOpId<FormFieldElement>[];
if (!fieldElementsWithOpid.length) {
const elementIndex = parseInt(opid.split("__")[1], 10);
return formFieldElements[elementIndex] || null;
}
if (fieldElementsWithOpid.length > 1) {
// eslint-disable-next-line no-console
console.warn(`More than one element found with opid ${opid}`);
}
return fieldElementsWithOpid[0];
}
/**
* Sorts the AutofillFieldElements map by the elementNumber property.
* @private
*/
private sortAutofillFieldElementsMap() {
if (!this.autofillFieldElements.size) {
return;
}
this.autofillFieldElements = new Map(
[...this.autofillFieldElements].sort((a, b) => a[1].elementNumber - b[1].elementNumber),
);
}
/**
* Formats and returns the AutofillPageDetails object
*
* @param autofillFormsData - The data for all the forms found in the page
* @param autofillFieldsData - The data for all the fields found in the page
*/
private getFormattedPageDetails(
autofillFormsData: Record<string, AutofillForm>,
autofillFieldsData: AutofillField[],
): AutofillPageDetails {
return {
title: document.title,
url: (document.defaultView || globalThis).location.href,
documentUrl: document.location.href,
forms: autofillFormsData,
fields: autofillFieldsData,
collectedTimestamp: Date.now(),
};
}
/**
* Re-checks the visibility for all form fields and updates the
* cached data to reflect the most recent visibility state.
*
* @private
*/
private updateCachedAutofillFieldVisibility() {
this.autofillFieldElements.forEach(async (autofillField, element) => {
const previouslyViewable = autofillField.viewable;
autofillField.viewable = await this.domElementVisibilityService.isElementViewable(element);
if (!previouslyViewable && autofillField.viewable) {
this.setupOverlayOnField(element, autofillField);
}
});
}
/**
* Queries the DOM for all the forms elements and
* returns a collection of AutofillForm objects.
* @returns {Record<string, AutofillForm>}
* @private
*/
private buildAutofillFormsData(formElements: Node[]): Record<string, AutofillForm> {
for (let index = 0; index < formElements.length; index++) {
const formElement = formElements[index] as ElementWithOpId<HTMLFormElement>;
formElement.opid = `__form__${index}`;
const existingAutofillForm = this._autofillFormElements.get(formElement);
if (existingAutofillForm) {
existingAutofillForm.opid = formElement.opid;
this._autofillFormElements.set(formElement, existingAutofillForm);
continue;
}
this._autofillFormElements.set(formElement, {
opid: formElement.opid,
htmlAction: this.getFormActionAttribute(formElement),
htmlName: this.getPropertyOrAttribute(formElement, "name"),
htmlID: this.getPropertyOrAttribute(formElement, "id"),
htmlMethod: this.getPropertyOrAttribute(formElement, "method"),
});
}
return this.getFormattedAutofillFormsData();
}
/**
* Returns the action attribute of the form element. If the action attribute
* is a relative path, it will be converted to an absolute path.
* @param {ElementWithOpId<HTMLFormElement>} element
* @returns {string}
* @private
*/
private getFormActionAttribute(element: ElementWithOpId<HTMLFormElement>): string {
return new URL(this.getPropertyOrAttribute(element, "action"), globalThis.location.href).href;
}
/**
* Iterates over all known form elements and returns an AutofillForm object
* containing a key value pair of the form element's opid and the form data.
* @returns {Record<string, AutofillForm>}
* @private
*/
private getFormattedAutofillFormsData(): Record<string, AutofillForm> {
const autofillForms: Record<string, AutofillForm> = {};
const autofillFormElements = Array.from(this._autofillFormElements);
for (let index = 0; index < autofillFormElements.length; index++) {
const [formElement, autofillForm] = autofillFormElements[index];
autofillForms[formElement.opid] = autofillForm;
}
return autofillForms;
}
/**
* Queries the DOM for all the field elements and
* returns a list of AutofillField objects.
* @returns {Promise<AutofillField[]>}
* @private
*/
private async buildAutofillFieldsData(
formFieldElements: FormFieldElement[],
): Promise<AutofillField[]> {
const autofillFieldElements = this.getAutofillFieldElements(100, formFieldElements);
const autofillFieldDataPromises = autofillFieldElements.map(this.buildAutofillFieldItem);
return Promise.all(autofillFieldDataPromises);
}
/**
* Queries the DOM for all the field elements that can be autofilled,
* and returns a list limited to the given `fieldsLimit` number that
* is ordered by priority.
* @param {number} fieldsLimit - The maximum number of fields to return
* @param {FormFieldElement[]} previouslyFoundFormFieldElements - The list of all the field elements
* @returns {FormFieldElement[]}
* @private
*/
private getAutofillFieldElements(
fieldsLimit?: number,
previouslyFoundFormFieldElements?: FormFieldElement[],
): FormFieldElement[] {
let formFieldElements = previouslyFoundFormFieldElements;
if (!formFieldElements) {
formFieldElements = this.domQueryService.query<FormFieldElement>(
globalThis.document.documentElement,
this.formFieldQueryString,
(node: Node) => this.isNodeFormFieldElement(node),
this.mutationObserver,
);
}
if (!fieldsLimit || formFieldElements.length <= fieldsLimit) {
return formFieldElements;
}
const priorityFormFields: FormFieldElement[] = [];
const unimportantFormFields: FormFieldElement[] = [];
const unimportantFieldTypesSet = new Set(["checkbox", "radio"]);
for (const element of formFieldElements) {
if (priorityFormFields.length >= fieldsLimit) {
return priorityFormFields;
}
const fieldType = this.getPropertyOrAttribute(element, "type")?.toLowerCase();
if (unimportantFieldTypesSet.has(fieldType)) {
unimportantFormFields.push(element);
continue;
}
priorityFormFields.push(element);
}
const numberUnimportantFieldsToInclude = fieldsLimit - priorityFormFields.length;
for (let index = 0; index < numberUnimportantFieldsToInclude; index++) {
priorityFormFields.push(unimportantFormFields[index]);
}
return priorityFormFields;
}
/**
* Builds an AutofillField object from the given form element. Will only return
* shared field values if the element is a span element. Will not return any label
* values if the element is a hidden input element.
*
* @param element - The form field element to build the AutofillField object from
* @param index - The index of the form field element
*/
private buildAutofillFieldItem = async (
element: ElementWithOpId<FormFieldElement>,
index: number,
): Promise<AutofillField | null> => {
if (element.closest("button[type='submit']")) {
return null;
}
element.opid = `__${index}`;
const existingAutofillField = this.autofillFieldElements.get(element);
if (index >= 0 && existingAutofillField) {
existingAutofillField.opid = element.opid;
existingAutofillField.elementNumber = index;
this.autofillFieldElements.set(element, existingAutofillField);
return existingAutofillField;
}
const autofillFieldBase = {
opid: element.opid,
elementNumber: index,
maxLength: this.getAutofillFieldMaxLength(element),
viewable: await this.domElementVisibilityService.isElementViewable(element),
htmlID: this.getPropertyOrAttribute(element, "id"),
htmlName: this.getPropertyOrAttribute(element, "name"),
htmlClass: this.getPropertyOrAttribute(element, "class"),
tabindex: this.getPropertyOrAttribute(element, "tabindex"),
title: this.getPropertyOrAttribute(element, "title"),
tagName: this.getAttributeLowerCase(element, "tagName"),
dataSetValues: this.getDataSetValues(element),
};
if (!autofillFieldBase.viewable) {
this.elementInitializingIntersectionObserver.add(element);
this.intersectionObserver?.observe(element);
}
if (elementIsSpanElement(element)) {
this.cacheAutofillFieldElement(index, element, autofillFieldBase);
return autofillFieldBase;
}
let autofillFieldLabels = {};
const elementType = this.getAttributeLowerCase(element, "type");
if (elementType !== "hidden") {
autofillFieldLabels = {
"label-tag": this.createAutofillFieldLabelTag(element as FillableFormFieldElement),
"label-data": this.getPropertyOrAttribute(element, "data-label"),
"label-aria": this.getPropertyOrAttribute(element, "aria-label"),
"label-top": this.createAutofillFieldTopLabel(element),
"label-right": this.createAutofillFieldRightLabel(element),
"label-left": this.createAutofillFieldLeftLabel(element),
placeholder: this.getPropertyOrAttribute(element, "placeholder"),
};
}
const fieldFormElement = (element as ElementWithOpId<FillableFormFieldElement>).form;
const autofillField = {
...autofillFieldBase,
...autofillFieldLabels,
rel: this.getPropertyOrAttribute(element, "rel"),
type: elementType,
value: this.getElementValue(element),
checked: this.getAttributeBoolean(element, "checked"),
autoCompleteType: this.getAutoCompleteAttribute(element),
disabled: this.getAttributeBoolean(element, "disabled"),
readonly: this.getAttributeBoolean(element, "readonly"),
selectInfo: elementIsSelectElement(element)
? this.getSelectElementOptions(element as HTMLSelectElement)
: null,
form: fieldFormElement ? this.getPropertyOrAttribute(fieldFormElement, "opid") : null,
"aria-hidden": this.getAttributeBoolean(element, "aria-hidden", true),
"aria-disabled": this.getAttributeBoolean(element, "aria-disabled", true),
"aria-haspopup": this.getAttributeBoolean(element, "aria-haspopup", true),
"data-stripe": this.getPropertyOrAttribute(element, "data-stripe"),
};
this.cacheAutofillFieldElement(index, element, autofillField);
return autofillField;
};
/**
* Caches the autofill field element and its data.
* Will not cache the element if the index is less than 0.
*
* @param index - The index of the autofill field element
* @param element - The autofill field element to cache
* @param autofillFieldData - The autofill field data to cache
*/
private cacheAutofillFieldElement(
index: number,
element: ElementWithOpId<FormFieldElement>,
autofillFieldData: AutofillField,
) {
if (index < 0) {
return;
}
this.autofillFieldElements.set(element, autofillFieldData);
}
/**
* Identifies the autocomplete attribute associated with an element and returns
* the value of the attribute if it is not set to "off".
* @param {ElementWithOpId<FormFieldElement>} element
* @returns {string}
* @private
*/
private getAutoCompleteAttribute(element: ElementWithOpId<FormFieldElement>): string {
return (
this.getPropertyOrAttribute(element, "x-autocompletetype") ||
this.getPropertyOrAttribute(element, "autocompletetype") ||
this.getPropertyOrAttribute(element, "autocomplete")
);
}
/**
* Returns the attribute of an element as a lowercase value.
* @param {ElementWithOpId<FormFieldElement>} element
* @param {string} attributeName
* @returns {string}
* @private
*/
private getAttributeLowerCase(
element: ElementWithOpId<FormFieldElement>,
attributeName: string,
): string {
return this.getPropertyOrAttribute(element, attributeName)?.toLowerCase();
}
/**
* Returns the value of an element's property or attribute.
* @returns {AutofillField[]}
* @private
*/
private getFormattedAutofillFieldsData(): AutofillField[] {
return Array.from(this.autofillFieldElements.values());
}
/**
* Creates a label tag used to autofill the element pulled from a label
* associated with the element's id, name, parent element or from an
* associated description term element if no other labels can be found.
* Returns a string containing all the `textContent` or `innerText`
* values of the label elements.
* @param {FillableFormFieldElement} element
* @returns {string}
* @private
*/
private createAutofillFieldLabelTag(element: FillableFormFieldElement): string {
const labelElementsSet: Set<HTMLElement> = new Set(element.labels);
if (labelElementsSet.size) {
return this.createLabelElementsTag(labelElementsSet);
}
const labelElements: NodeListOf<HTMLLabelElement> | null = this.queryElementLabels(element);
for (let labelIndex = 0; labelIndex < labelElements?.length; labelIndex++) {
labelElementsSet.add(labelElements[labelIndex]);
}
let currentElement: HTMLElement | null = element;
while (currentElement && currentElement !== document.documentElement) {
if (elementIsLabelElement(currentElement)) {
labelElementsSet.add(currentElement);
}
currentElement = currentElement.parentElement?.closest("label");
}
if (
!labelElementsSet.size &&
elementIsDescriptionDetailsElement(element.parentElement) &&
elementIsDescriptionTermElement(element.parentElement.previousElementSibling)
) {
labelElementsSet.add(element.parentElement.previousElementSibling);
}
return this.createLabelElementsTag(labelElementsSet);
}
/**
* Queries the DOM for label elements associated with the given element
* by id or name. Returns a NodeList of label elements or null if none
* are found.
* @param {FillableFormFieldElement} element
* @returns {NodeListOf<HTMLLabelElement> | null}
* @private
*/
private queryElementLabels(
element: FillableFormFieldElement,
): NodeListOf<HTMLLabelElement> | null {
let labelQuerySelectors = element.id ? `label[for="${element.id}"]` : "";
if (element.name) {
const forElementNameSelector = `label[for="${element.name}"]`;
labelQuerySelectors = labelQuerySelectors
? `${labelQuerySelectors}, ${forElementNameSelector}`
: forElementNameSelector;
}
if (!labelQuerySelectors) {
return null;
}
return (element.getRootNode() as Document | ShadowRoot).querySelectorAll(
labelQuerySelectors.replace(/\n/g, ""),
);
}
/**
* Map over all the label elements and creates a
* string of the text content of each label element.
* @param {Set<HTMLElement>} labelElementsSet
* @returns {string}
* @private
*/
private createLabelElementsTag = (labelElementsSet: Set<HTMLElement>): string => {
return Array.from(labelElementsSet)
.map((labelElement) => {
const textContent: string | null = labelElement
? labelElement.textContent || labelElement.innerText
: null;
return this.trimAndRemoveNonPrintableText(textContent || "");
})
.join("");
};
/**
* Gets the maxLength property of the passed FormFieldElement and
* returns the value or null if the element does not have a
* maxLength property. If the element has a maxLength property
* greater than 999, it will return 999.
* @param {FormFieldElement} element
* @returns {number | null}
* @private
*/
private getAutofillFieldMaxLength(element: FormFieldElement): number | null {
const elementHasMaxLengthProperty =
elementIsInputElement(element) || elementIsTextAreaElement(element);
const elementMaxLength =
elementHasMaxLengthProperty && element.maxLength > -1 ? element.maxLength : 999;
return elementHasMaxLengthProperty ? Math.min(elementMaxLength, 999) : null;
}
/**
* Iterates over the next siblings of the passed element and
* returns a string of the text content of each element. Will
* stop iterating if it encounters a new section element.
* @param {FormFieldElement} element
* @returns {string}
* @private
*/
private createAutofillFieldRightLabel(element: FormFieldElement): string {
const labelTextContent: string[] = [];
let currentElement: ChildNode = element;
while (currentElement && currentElement.nextSibling) {
currentElement = currentElement.nextSibling;
if (this.isNewSectionElement(currentElement)) {
break;
}
const textContent = this.getTextContentFromElement(currentElement);
if (textContent) {
labelTextContent.push(textContent);
}
}
return labelTextContent.join("");
}
/**
* Recursively gets the text content from an element's previous siblings
* and returns a string of the text content of each element.
* @param {FormFieldElement} element
* @returns {string}
* @private
*/
private createAutofillFieldLeftLabel(element: FormFieldElement): string {
const labelTextContent: string[] = this.recursivelyGetTextFromPreviousSiblings(element);
return labelTextContent.reverse().join("");
}
/**
* Assumes that the input elements that are to be autofilled are within a
* table structure. Queries the previous sibling of the parent row that
* the input element is in and returns the text content of the cell that
* is in the same column as the input element.
* @param {FormFieldElement} element
* @returns {string | null}
* @private
*/
private createAutofillFieldTopLabel(element: FormFieldElement): string | null {
const tableDataElement = element.closest("td");
if (!tableDataElement) {
return null;
}
const tableDataElementIndex = tableDataElement.cellIndex;
if (tableDataElementIndex < 0) {
return null;
}
const parentSiblingTableRowElement = tableDataElement.closest("tr")
?.previousElementSibling as HTMLTableRowElement;
return parentSiblingTableRowElement?.cells?.length > tableDataElementIndex
? this.getTextContentFromElement(parentSiblingTableRowElement.cells[tableDataElementIndex])
: null;
}
/**
* Check if the element's tag indicates that a transition to a new section of the
* page is occurring. If so, we should not use the element or its children in order
* to get autofill context for the previous element.
* @param {HTMLElement} currentElement
* @returns {boolean}
* @private
*/
private isNewSectionElement(currentElement: HTMLElement | Node): boolean {
if (!currentElement) {
return true;
}
const transitionalElementTagsSet = new Set([
"html",
"body",
"button",
"form",
"head",
"iframe",
"input",
"option",
"script",
"select",
"table",
"textarea",
]);
return (
"tagName" in currentElement &&
transitionalElementTagsSet.has(currentElement.tagName.toLowerCase())
);
}
/**
* Gets the text content from a passed element, regardless of whether it is a
* text node, an element node or an HTMLElement.
* @param {Node | HTMLElement} element
* @returns {string}
* @private
*/
private getTextContentFromElement(element: Node | HTMLElement): string {
if (element.nodeType === Node.TEXT_NODE) {
return this.trimAndRemoveNonPrintableText(element.nodeValue);
}
return this.trimAndRemoveNonPrintableText(
element.textContent || (element as HTMLElement).innerText,
);
}
/**
* Removes non-printable characters from the passed text
* content and trims leading and trailing whitespace.
* @param {string} textContent
* @returns {string}
* @private
*/
private trimAndRemoveNonPrintableText(textContent: string): string {
return (textContent || "")
.replace(/[^\x20-\x7E]+|\s+/g, " ") // Strip out non-primitive characters and replace multiple spaces with a single space
.trim(); // Trim leading and trailing whitespace
}
/**
* Get the text content from the previous siblings of the element. If
* no text content is found, recursively get the text content from the
* previous siblings of the parent element.
* @param {FormFieldElement} element
* @returns {string[]}
* @private
*/
private recursivelyGetTextFromPreviousSiblings(element: Node | HTMLElement): string[] {
const textContentItems: string[] = [];
let currentElement = element;
while (currentElement && currentElement.previousSibling) {
// Ensure we are capturing text content from nodes and elements.
currentElement = currentElement.previousSibling;
if (this.isNewSectionElement(currentElement)) {
return textContentItems;
}
const textContent = this.getTextContentFromElement(currentElement);
if (textContent) {
textContentItems.push(textContent);
}
}
if (!currentElement || textContentItems.length) {
return textContentItems;
}
// Prioritize capturing text content from elements rather than nodes.
currentElement = currentElement.parentElement || currentElement.parentNode;
if (!currentElement) {
return textContentItems;
}
let siblingElement = nodeIsElement(currentElement)
? currentElement.previousElementSibling
: currentElement.previousSibling;
while (siblingElement?.lastChild && !this.isNewSectionElement(siblingElement)) {
siblingElement = siblingElement.lastChild;
}
if (this.isNewSectionElement(siblingElement)) {
return textContentItems;
}
const textContent = this.getTextContentFromElement(siblingElement);
if (textContent) {
textContentItems.push(textContent);
return textContentItems;
}
return this.recursivelyGetTextFromPreviousSiblings(siblingElement);
}
/**
* Gets the value of the element. If the element is a checkbox, returns a checkmark if the
* checkbox is checked, or an empty string if it is not checked. If the element is a hidden
* input, returns the value of the input if it is less than 254 characters, or a truncated
* value if it is longer than 254 characters.
* @param {FormFieldElement} element
* @returns {string}
* @private
*/
private getElementValue(element: FormFieldElement): string {
if (!elementIsFillableFormField(element)) {
const spanTextContent = element.textContent || element.innerText;
return spanTextContent || "";
}
const elementValue = element.value || "";
const elementType = String(element.type).toLowerCase();
if ("checked" in element && elementType === "checkbox") {
return element.checked ? "✓" : "";
}
if (elementType === "hidden") {
const inputValueMaxLength = 254;
return elementValue.length > inputValueMaxLength
? `${elementValue.substring(0, inputValueMaxLength)}...SNIPPED`
: elementValue;
}
return elementValue;
}
/**
* Captures the `data-*` attribute metadata to help with validating the autofill data.
*
* @param element - The form field element to capture the `data-*` attribute metadata from
*/
private getDataSetValues(element: ElementWithOpId<FormFieldElement>): string {
let datasetValues = "";
const dataset = element.dataset;
for (const key in dataset) {
datasetValues += `${key}: ${dataset[key]}, `;
}
return datasetValues;
}
/**
* Get the options from a select element and return them as an array
* of arrays indicating the select element option text and value.
* @param {HTMLSelectElement} element
* @returns {{options: (string | null)[][]}}
* @private
*/
private getSelectElementOptions(element: HTMLSelectElement): { options: (string | null)[][] } {
const options = Array.from(element.options).map((option) => {
const optionText = option.text
? String(option.text)
.toLowerCase()
.replace(/[\s~`!@$%^&#*()\-_+=:;'"[\]|\\,<.>?]/gm, "") // Remove whitespace and punctuation
: null;
return [optionText, option.value];
});
return { options };
}
/**
* Queries all potential form and field elements from the DOM and returns
* a collection of form and field elements. Leverages the TreeWalker API
* to deep query Shadow DOM elements.
*/
private queryAutofillFormAndFieldElements(): {
formElements: HTMLFormElement[];
formFieldElements: FormFieldElement[];
} {
const formElements: HTMLFormElement[] = [];
const formFieldElements: FormFieldElement[] = [];
const queriedElements = this.domQueryService.query<HTMLElement>(
globalThis.document.documentElement,
`form, ${this.formFieldQueryString}`,
(node: Node) => {
if (nodeIsFormElement(node)) {
formElements.push(node);
return true;
}
if (this.isNodeFormFieldElement(node)) {
formFieldElements.push(node as FormFieldElement);
return true;
}
return false;
},
this.mutationObserver,
);
if (formElements.length || formFieldElements.length) {
return { formElements, formFieldElements };
}
for (let index = 0; index < queriedElements.length; index++) {
const element = queriedElements[index];
if (elementIsFormElement(element)) {
formElements.push(element);
continue;
}
if (this.isNodeFormFieldElement(element)) {
formFieldElements.push(element);
}
}
return { formElements, formFieldElements };
}
/**
* Checks if the passed node is a form field element.
* @param {Node} node
* @returns {boolean}
* @private
*/
private isNodeFormFieldElement(node: Node): boolean {
if (!nodeIsElement(node)) {
return false;
}
const nodeTagName = node.tagName.toLowerCase();
const nodeIsSpanElementWithAutofillAttribute =
nodeTagName === "span" && node.hasAttribute("data-bwautofill");
if (nodeIsSpanElementWithAutofillAttribute) {
return true;
}
const nodeHasBwIgnoreAttribute = node.hasAttribute("data-bwignore");
const nodeIsValidInputElement =
nodeTagName === "input" && !this.ignoredInputTypes.has((node as HTMLInputElement).type);
if (nodeIsValidInputElement && !nodeHasBwIgnoreAttribute) {
return true;
}
return this.nonInputFormFieldTags.has(nodeTagName) && !nodeHasBwIgnoreAttribute;
}
/**
* Sets up a mutation observer on the body of the document. Observes changes to
* DOM elements to ensure we have an updated set of autofill field data.
* @private
*/
private setupMutationObserver() {
this.currentLocationHref = globalThis.location.href;
this.mutationObserver = new MutationObserver(this.handleMutationObserverMutation);
this.mutationObserver.observe(document.documentElement, {
attributes: true,
childList: true,
subtree: true,
});
}
/**
* Handles observed DOM mutations and identifies if a mutation is related to
* an autofill element. If so, it will update the autofill element data.
* @param {MutationRecord[]} mutations
* @private
*/
private handleMutationObserverMutation = (mutations: MutationRecord[]) => {
if (this.currentLocationHref !== globalThis.location.href) {
this.handleWindowLocationMutation();
return;
}
if (!this.mutationsQueue.length) {
requestIdleCallbackPolyfill(debounce(this.processMutations, 100), { timeout: 500 });
}
this.mutationsQueue.push(mutations);
};
/**
* Handles a mutation to the window location. Clears the autofill elements
* and updates the autofill elements after a timeout.
* @private
*/
private handleWindowLocationMutation() {
this.currentLocationHref = globalThis.location.href;
this.domRecentlyMutated = true;
if (this.autofillOverlayContentService) {
this.autofillOverlayContentService.pageDetailsUpdateRequired = true;
this.autofillOverlayContentService.clearUserFilledFields();
void this.sendExtensionMessage("closeAutofillInlineMenu", { forceCloseInlineMenu: true });
}
this.noFieldsFound = false;
this._autofillFormElements.clear();
this.autofillFieldElements.clear();
this.updateAutofillElementsAfterMutation();
}
/**
* Handles the processing of all mutations in the mutations queue. Will trigger
* within an idle callback to help with performance and prevent excessive updates.
*/
private processMutations = () => {
const queueLength = this.mutationsQueue.length;
if (!this.domQueryService.pageContainsShadowDomElements()) {
this.checkPageContainsShadowDom();
}
for (let queueIndex = 0; queueIndex < queueLength; queueIndex++) {
const mutations = this.mutationsQueue[queueIndex];
const processMutationRecords = () => {
this.processMutationRecords(mutations);
if (queueIndex === queueLength - 1 && this.domRecentlyMutated) {
this.updateAutofillElementsAfterMutation();
}
};
requestIdleCallbackPolyfill(processMutationRecords, { timeout: 500 });
}
this.mutationsQueue = [];
};