Welcome to mirror list, hosted at ThFree Co, Russian Federation.

keepassxc-browser.js « content « keepassxc-browser - github.com/keepassxreboot/keepassxc-browser.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 329cf49d7f2171fcce2048558f2cfc2f352c1f2b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
'use strict';

const ManualFill = {
    NONE: 0,
    PASS: 1,
    BOTH: 2
};

const acceptedOTPFields = [
    '2fa',
    'auth',
    'challenge',
    'code',
    'mfa',
    'otp',
    'token'
];

// Contains already called method names
const _called = {};
_called.retrieveCredentials = false;
_called.clearLogins = false;
_called.manualFillRequested = ManualFill.NONE;
let _singleInputEnabledForPage = false;
let _databaseClosed = true;
const _maximumInputs = 100;
const _maximumMutations = 200;

// Count of detected form fields on the page
var _detectedFields = 0;

// Element id's containing input fields detected by MutationObserver
const _observerIds = [];

// Document URL
let _documentURL = document.location.href;

// These are executed in each frame
browser.runtime.onMessage.addListener(async function(req, sender) {
    if ('action' in req) {
        if (req.action === 'fill_user_pass_with_specific_login') {
            kpxc.fillWithSpecificLogin(req.id);
        } else if (req.action === 'fill_username_password') {
            _called.manualFillRequested = ManualFill.BOTH;
            await kpxc.receiveCredentialsIfNecessary();
            kpxc.fillInFromActiveElement(false);
        } else if (req.action === 'fill_password') {
            _called.manualFillRequested = ManualFill.PASS;
            await kpxc.receiveCredentialsIfNecessary();
            kpxc.fillInFromActiveElement(false, true); // passOnly to true
        } else if (req.action === 'fill_totp') {
            await kpxc.receiveCredentialsIfNecessary();
            kpxc.fillInFromActiveElementTOTPOnly();
        } else if (req.action === 'clear_credentials') {
            kpxcEvents.clearCredentials();
            return Promise.resolve();
        } else if (req.action === 'activated_tab') {
            kpxcEvents.triggerActivatedTab();
            return Promise.resolve();
        } else if (req.action === 'ignore_site') {
            kpxc.ignoreSite(req.args);
        } else if (req.action === 'check_database_hash' && 'hash' in req) {
            kpxc.detectDatabaseChange(req.hash);
        } else if (req.action === 'remember_credentials') {
            kpxc.contextMenuRememberCredentials();
        } else if (req.action === 'choose_credential_fields') {
            kpxcDefine.init();
        } else if (req.action === 'redetect_fields') {
            const response = await browser.runtime.sendMessage({
                action: 'load_settings'
            });
            kpxc.settings = response;
            kpxc.initCredentialFields(true);
        } else if (req.action === 'show_password_generator') {
            kpxcPasswordDialog.trigger();
        } else if (req.action === 'add_username_only_option') {
            kpxc.addToSitePreferences();
        }
    }
});

function _f(fieldId) {
    const inputs = document.querySelectorAll(`input[data-kpxc-id='${fieldId}']`);
    return inputs.length > 0 ? inputs[0] : null;
}

function _fs(fieldId) {
    const inputs = document.querySelectorAll(`input[data-kpxc-id='${fieldId}'], select[data-kpxc-id='${fieldId}']`);
    return inputs.length > 0 ? inputs[0] : null;
}


const kpxcForm = {};
kpxcForm.passwordInputs = [];

kpxcForm.init = function(form, credentialFields) {
    if (!form.getAttribute('kpxcForm-initialized') && (credentialFields.password || credentialFields.username)) {
        form.setAttribute('kpxcForm-initialized', true);
        kpxcForm.setInputFields(form, credentialFields);
        form.addEventListener('submit', kpxcForm.onSubmit);

        const submitButton = kpxc.getFormSubmitButton(form);
        if (submitButton !== undefined) {
            submitButton.addEventListener('click', kpxcForm.onSubmit);
        }
    }
};

kpxcForm.destroy = function(form, credentialFields) {
    if (form === false && credentialFields) {
        const field = _f(credentialFields.password) || _f(credentialFields.username);
        if (field) {
            form = kpxc.getForm(field);
            if (form && form.length > 0) {
                form.removeEventListener('submit', kpxcForm.onSubmit);
            }
        }
    }

    kpxcForm.passwordInputs = [];
};

kpxcForm.setInputFields = function(form, credentialFields) {
    form.setAttribute('kpxcUsername', credentialFields.username);
    form.setAttribute('kpxcPassword', credentialFields.password);

    // Save all the password input fields from the form
    kpxcForm.passwordInputs = Array.from(form.elements).filter(e => e.nodeName === 'INPUT' && e.type === 'password');
};

kpxcForm.onSubmit = async function(e) {
    if (!e.isTrusted) {
        return;
    }

    const form = this.nodeName === 'FORM' ? this : this.form;
    const usernameId = form.getAttribute('kpxcUsername');
    const passwordId = form.getAttribute('kpxcPassword');
    const usernameField = _f(usernameId);
    const passwordField = _f(passwordId);
    let usernameValue = '';
    let passwordValue = '';

    if (usernameField) {
        usernameValue = usernameField.value || usernameField.placeholder;
    } else if (kpxc.credentials.length === 1) {
        // Single entry found for the page, use the username of it instead of an empty one
        usernameValue = kpxc.credentials[0].login;
    }

    // Check if the form has three password fields -> a possible password change form
    if (kpxcForm.passwordInputs.length >= 2) {
        passwordValue = kpxcForm.getNewPassword();
    } else if (passwordField) {
        // Use the combination password field instead
        passwordValue = passwordField.value;
    }

    // Return if credentials are already found
    if (kpxc.credentials.some(c => c.login === usernameValue && c.password === passwordValue)) {
        return;
    }

    browser.runtime.sendMessage({
        action: 'page_set_submitted',
        args: [ true, usernameValue, passwordValue, trimURL(window.top.location.href), kpxc.credentials ]
    });

    // Show the banner if the page does not reload
    kpxc.rememberCredentials(usernameValue, passwordValue);
};

// Retrieve new password from a form with three elements: Current, New, Repeat New
kpxcForm.getNewPassword = function() {
    if (kpxcForm.passwordInputs.length < 2) {
        return '';
    }

    // Just two password fields, current and new
    if (kpxcForm.passwordInputs.length === 2 &&
        kpxcForm.passwordInputs[0] !== kpxcForm.passwordInputs[1]) {
        return kpxcForm.passwordInputs[1].value;
    }

    // Choose the last three password fields. The first ones are almost always for something else
    const current = kpxcForm.passwordInputs[kpxcForm.passwordInputs.length - 3].value;
    const newPass = kpxcForm.passwordInputs[kpxcForm.passwordInputs.length - 2].value;
    const repeatNew = kpxcForm.passwordInputs[kpxcForm.passwordInputs.length - 1].value;

    if (current !== newPass && newPass !== '' && newPass === repeatNew) {
        return newPass;
    } else if (current === newPass && repeatNew !== newPass) {
        // Reverse form where current password is at the bottom
        return repeatNew;
    }

    return '';
};


const kpxcFields = {};
kpxcFields.inputQueryPattern = 'input[type=\'text\'], input[type=\'email\'], input[type=\'password\'], input[type=\'tel\'], input[type=\'number\'], input[type=\'username\'], input:not([type])';

// copied from Sizzle.js
kpxcFields.rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g;
kpxcFields.fcssescape = function(ch, asCodePoint) {
    if (asCodePoint) {
        // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
        if (ch === '\0') {
            return '\uFFFD';
        }

        // Control characters and (dependent upon position) numbers get escaped as code points
        return ch.slice(0, -1) + '\\' + ch.charCodeAt(ch.length - 1).toString(16) + ' ';
    }

    // Other potentially-special ASCII characters get backslash-escaped
    return '\\' + ch;
};

// Unique number as new IDs for input fields
kpxcFields.uniqueNumber = 342845638;
// Objects with combination of username + password fields
kpxcFields.combinations = [];

kpxcFields.setUniqueId = function(field) {
    if (field && !field.getAttribute('data-kpxc-id')) {
        // Use ID of field if it is unique
        const fieldId = field.getAttribute('id');
        if (fieldId) {
            const foundIds = document.querySelectorAll('input#' + kpxcFields.prepareId(fieldId));
            if (foundIds.length === 1) {
                field.setAttribute('data-kpxc-id', fieldId);
                return;
            }
        }

        // Create own ID if no ID is set for this field
        kpxcFields.uniqueNumber += 1;
        field.setAttribute('data-kpxc-id', 'kpxcpw' + String(kpxcFields.uniqueNumber));
    }
};

kpxcFields.prepareId = function(id) {
    return (id + '').replace(kpxcFields.rcssescape, kpxcFields.fcssescape);
};

// Checks if input field is a search field. Attributes or form action containing 'search', or parent element holding
// role="search" will be identified as a search field.
kpxcFields.isSearchField = function(target) {
    const attributes = target.attributes;

    // Check element attributes
    for (const attr of attributes) {
        if ((attr.value && (attr.value.toLowerCase().includes('search')) || attr.value === 'q')) {
            return true;
        }
    }

    // Check closest form
    const closestForm = kpxc.getForm(target);
    if (closestForm) {
        // Check form action
        const formAction = closestForm.getAttribute('action');
        if (formAction && (formAction.toLowerCase().includes('search') &&
            !formAction.toLowerCase().includes('research'))) {
            return true;
        }

        // Check form class and id
        const closestFormId = closestForm.getAttribute('id');
        const closestFormClass = closestForm.className;
        if (closestFormClass && (closestForm.className.toLowerCase().includes('search') ||
            (closestFormId && closestFormId.toLowerCase().includes('search') && !closestFormId.toLowerCase().includes('research')))) {
            return true;
        }
    }

    // Check parent elements for role='search'
    if (target.closest('[role~=\'search\']')) {
        return true;
    }

    return false;
};

kpxcFields.isVisible = function(field) {
    const rect = field.getBoundingClientRect();

    // Check CSS visibility
    const fieldStyle = getComputedStyle(field);
    if (fieldStyle.visibility && (fieldStyle.visibility === 'hidden' || fieldStyle.visibility === 'collapse')) {
        return false;
    }

    // Check element position and size
    if (rect.x < 0 || rect.y < 0 || rect.width < 8 || rect.height < 8) {
        return false;
    }

    return true;
};

kpxcFields.isAutocompleteAppropriate = function(field) {
    const autocomplete = field.getLowerCaseAttribute('autocomplete');
    return !(autocomplete === 'off' || autocomplete === 'new-password');
};

kpxcFields.getAllFields = function() {
    const fields = [];
    const inputs = kpxcObserverHelper.getInputs(document);

    for (const i of inputs) {
        if (kpxcFields.isVisible(i) && !kpxcFields.isSearchField(i) && kpxcFields.isAutocompleteAppropriate(i)) {
            kpxcFields.setUniqueId(i);
            fields.push(i);
        }
    }

    _detectedFields = fields.length;

    // Show add username-only option for the site in popup
    if (!_singleInputEnabledForPage &&
        fields.length === 1 && fields[0].getLowerCaseAttribute('type') !== 'password') {
        browser.runtime.sendMessage({
            action: 'username_field_detected',
            args: true
        });
    }

    return fields;
};

kpxcFields.prepareVisibleFieldsWithID = function(pattern) {
    const patterns = document.querySelectorAll(pattern);
    for (const i of patterns) {
        if (kpxcFields.isVisible(i) && i.style.visibility !== 'hidden' && i.style.visibility !== 'collapsed') {
            kpxcFields.setUniqueId(i);
        }
    }
};

kpxcFields.getAllCombinations = function(inputs) {
    const fields = [];
    let uField = null;

    for (const i of inputs) {
        if (i) {
            if (i.getLowerCaseAttribute('type') === 'password') {
                const uId = (!uField || uField.length < 1) ? null : uField.getAttribute('data-kpxc-id');

                const combination = {
                    username: uId,
                    password: i.getAttribute('data-kpxc-id')
                };
                fields.push(combination);

                // Reset selected username field
                uField = null;
            } else {
                // Username field
                uField = i;
            }
        }
    }

    if (_singleInputEnabledForPage && fields.length === 0 && uField) {
        const combination = {
            username: uField.getAttribute('data-kpxc-id'),
            password: null
        };
        fields.push(combination);
    }

    return fields;
};

kpxcFields.getCombination = function(givenType, fieldId) {
    if (kpxcFields.combinations.length === 0) {
        if (kpxcFields.useDefinedCredentialFields()) {
            return kpxcFields.combinations[0];
        }
    }
    // Use defined credential fields (already loaded into combinations)
    const location = kpxc.getDocumentLocation();
    if (kpxc.settings['defined-custom-fields'] && kpxc.settings['defined-custom-fields'][location]) {
        return kpxcFields.combinations[0];
    }

    for (const c of kpxcFields.combinations) {
        if (c[givenType] === fieldId) {
            return c;
        }
    }

    // Find new combination
    let combination = {
        username: null,
        password: null
    };

    let newCombi = false;
    if (givenType === 'username') {
        const passwordField = kpxcFields.getPasswordField(fieldId, true);
        let passwordId = null;
        if (passwordField) {
            passwordId = kpxcFields.prepareId(passwordField.getAttribute('data-kpxc-id'));
        }
        combination = {
            username: fieldId,
            password: passwordId
        };
        newCombi = true;
    } else if (givenType === 'password') {
        const usernameField = kpxcFields.getUsernameField(fieldId, true);
        let usernameId = null;
        if (usernameField) {
            usernameId = kpxcFields.prepareId(usernameField.getAttribute('data-kpxc-id'));
        }
        combination = {
            username: usernameId,
            password: fieldId
        };
        newCombi = true;
    }

    if (combination.username || combination.password) {
        kpxcFields.combinations.push(combination);
    }

    if (combination.username) {
        if (kpxc.credentials.length > 0) {
            kpxc.preparePageForMultipleCredentials(kpxc.credentials);
        }
    }

    if (newCombi) {
        combination.isNew = true;
    }
    return combination;
};

/**
* Return the username field or null if it not exists
*/
kpxcFields.getUsernameField = async function(passwordId, checkDisabled) {
    const passwordField = _f(passwordId);
    if (!passwordField) {
        return null;
    }

    const form = kpxc.getForm(passwordField);
    let usernameField = null;

    // Search all inputs on this one form
    if (form) {
        const inputs = form.querySelectorAll(kpxcFields.inputQueryPattern);
        for (const i of inputs) {
            kpxcFields.setUniqueId(i);
            if (i.getAttribute('data-kpxc-id') === passwordId) {
                return false; // Break
            }

            if (i.getLowerCaseAttribute('type') === 'password') {
                return true; // Continue
            }

            if (kpxc.settings.showLoginFormIcon && await kpxc.passwordFilled() === false) {
                kpxcUsernameIcons.newIcon(usernameField);
            }
            usernameField = i;
        }
    } else {
        // Search all inputs on page
        const inputs = kpxcFields.getAllFields();
        kpxc.initPasswordGenerator(inputs);
        for (const i of inputs) {
            if (i.getAttribute('data-kpxc-id') === passwordId) {
                break;
            }

            if (i.getLowerCaseAttribute('type') === 'password') {
                continue;
            }

            usernameField = i;
        }
    }

    if (usernameField && !checkDisabled) {
        const usernameId = usernameField.getAttribute('data-kpxc-id');
        // Check if usernameField is already used by another combination
        for (const c of kpxcFields.combinations) {
            if (c.username === usernameId) {
                usernameField = null;
                break;
            }
        }
    }

    kpxcFields.setUniqueId(usernameField);
    return usernameField;
};

/**
* Return the password field or null if it not exists
*/
kpxcFields.getPasswordField = function(usernameId, checkDisabled) {
    const usernameField = _f(usernameId);
    if (!usernameField) {
        return null;
    }

    const form = kpxc.getForm(usernameField);
    let passwordField = null;

    // Search all inputs on this one form
    if (form) {
        const inputs = form.querySelectorAll('input[type=\'password\']');
        if (inputs.length > 0) {
            passwordField = inputs[0];
        }
        if (passwordField && passwordField.length < 1) {
            passwordField = null;
        }

        kpxcPasswordIcons.newIcon(kpxc.settings.usePasswordGeneratorIcons, passwordField, [], undefined, _databaseClosed);
    } else {
        // Search all inputs on page
        const inputs = kpxcFields.getAllFields();
        kpxc.initPasswordGenerator(inputs);

        let active = false;
        for (const i of inputs) {
            if (i.getAttribute('data-kpxc-id') === usernameId) {
                active = true;
            }
            if (active && i.getLowerCaseAttribute('type') === 'password') {
                passwordField = i;
                break;
            }
        }
    }

    if (passwordField && !checkDisabled) {
        const passwordId = passwordField.getAttribute('data-kpxc-id');
        // Check if passwordField is already used by another combination
        for (const c of kpxcFields.combinations) {
            if (c.password === passwordId) {
                passwordField = null;
                break;
            }
        }
    }

    kpxcFields.setUniqueId(passwordField);
    return passwordField;
};

kpxcFields.prepareCombinations = async function(combinations) {
    for (const c of combinations) {
        const pwField = _f(c.password);
        // Needed for auto-complete: don't overwrite manually filled-in password field
        if (pwField && !pwField.getAttribute('kpxcFields-onChange')) {
            pwField.setAttribute('kpxcFields-onChange', true);
            pwField.addEventListener('change', function() {
                this.setAttribute('unchanged', false);
            });
        }

        const fieldId = c.password || c.username;
        const field = _f(fieldId);

        // If no username field is found, handle the single password field as such
        const usernameField = c.username ? _f(c.username) : field;

        if (kpxc.settings.showLoginFormIcon && await kpxc.passwordFilled() === false) {
            kpxcUsernameIcons.newIcon(usernameField, _databaseClosed);
        }

        // Initialize form-submit for remembering credentials
        if (field) {
            const form = kpxc.getForm(field);
            if (form && form.length > 0) {
                kpxcForm.init(form, c);
            }
        }
    }
};

kpxcFields.useDefinedCredentialFields = function() {
    const location = kpxc.getDocumentLocation();
    if (kpxc.settings['defined-custom-fields'] && kpxc.settings['defined-custom-fields'][location]) {
        const creds = kpxc.settings['defined-custom-fields'][location];

        let found = _f(creds.username) || _f(creds.password);
        for (const i of creds.fields) {
            if (_fs(i)) {
                found = true;
                break;
            }
        }

        if (found) {
            const fields = {
                username: creds.username,
                password: creds.password,
                fields: creds.fields
            };
            kpxcFields.combinations = [];
            kpxcFields.combinations.push(fields);

            return true;
        }
    }

    return false;
};

const kpxcObserverHelper = {};

kpxcObserverHelper.inputTypes = [
    'text',
    'email',
    'password',
    'tel',
    'number',
    'username', // Note: Not a standard
    undefined, // Input field can be without any type. Include this and null to the list.
    null 
];

// Ignores all nodes that doesn't contain elements
kpxcObserverHelper.ignoredNode = function(target) {
    if (target.nodeType === Node.ATTRIBUTE_NODE ||
        target.nodeType === Node.TEXT_NODE ||
        target.nodeType === Node.CDATA_SECTION_NODE ||
        target.nodeType === Node.PROCESSING_INSTRUCTION_NODE ||
        target.nodeType === Node.COMMENT_NODE ||
        target.nodeType === Node.DOCUMENT_TYPE_NODE ||
        target.nodeType === Node.NOTATION_NODE) {
        return true;
    }
    return false;
};

kpxcObserverHelper.getInputs = function(target) {
    // Ignores target element if it's not an element node
    if (kpxcObserverHelper.ignoredNode(target)) {
        return [];
    }

    // Filter out any input fields with type 'hidden' right away
    const inputFields = [];
    Array.from(target.getElementsByTagName('input')).forEach((e) => {
        if (e.type !== 'hidden' && !e.readOnly) {
            inputFields.push(e);
        }
    });

    if (inputFields.length === 0) {
        return [];
    }

    // Do not allow more visible inputs than _maximumInputs (default value: 100) -> return the first 100
    if (inputFields.length > _maximumInputs) {
        return inputFields.slice(0, _maximumInputs);
    }

    // Only include input fields that match with kpxcObserverHelper.inputTypes
    const inputs = [];
    for (const i of inputFields) {
        let type = i.getLowerCaseAttribute('type');

        if (kpxcObserverHelper.inputTypes.includes(type)) {
            inputs.push(i);
        }
    }
    return inputs;
};

kpxcObserverHelper.getId = function(target) {
    return target.classList.length === 0 ? target.id : target.classList;
};

kpxcObserverHelper.ignoredElement = function(target) {
    // Ignore elements that do not have a className (including SVG)
    if (typeof target.className !== 'string') {
        return true;
    }

    // Ignore KeePassXC-Browser classes
    if (target.className && target.className !== undefined &&
        target.className.includes('kpxc')) {
        return true;
    }

    return false;
};

kpxcObserverHelper.handleObserverAdd = function(target) {
    if (kpxcObserverHelper.ignoredElement(target)) {
        return;
    }

    const inputs = kpxcObserverHelper.getInputs(target);
    if (inputs.length === 0) {
        return;
    }

    const neededLength = _detectedFields === 1 ? 0 : 1;
    const id = kpxcObserverHelper.getId(target);
    if (inputs.length > neededLength && !_observerIds.includes(id)) {
        // Save target element id for preventing multiple calls to initCredentialsFields()
        _observerIds.push(id);

        // Sometimes the settings haven't been loaded before new input fields are detected
        if (Object.keys(kpxc.settings).length === 0) {
            kpxc.init();
        } else {
            kpxc.initCredentialFields(true, inputs);
        }
    }
};

kpxcObserverHelper.handleObserverRemove = function(target) {
    if (kpxcObserverHelper.ignoredElement(target)) {
        return;
    }

    const inputs = kpxcObserverHelper.getInputs(target);
    if (inputs.length === 0) {
        return;
    }

    // Remove target element id from the list
    const id = kpxcObserverHelper.getId(target);
    if (_observerIds.includes(id)) {
        const index = _observerIds.indexOf(id);
        if (index >= 0) {
            _observerIds.splice(index, 1);
        }
    }
};

kpxcObserverHelper.detectURLChange = function() {
    if (_documentURL !== document.location.href) {
        _documentURL = document.location.href;
        kpxcEvents.clearCredentials();
        kpxc.initCredentialFields(true);
    }
};

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;



const kpxc = {};
kpxc.settings = {};
kpxc.u = null;
kpxc.p = null;
kpxc.url = null;
kpxc.submitUrl = null;
kpxc.credentials = [];

const initcb = async function() {
    try {
        const settings = await browser.runtime.sendMessage({
            action: 'load_settings'
        });

        kpxc.settings = settings;

        // Don't initialize MutationObserver if the site is ignored
        if (kpxc.siteIgnored()) {
            return;
        }

        if (kpxc.settings.useObserver) {
            kpxc.initObserver();
        }

        await kpxc.initCredentialFields();

        // Retrieve submitted credentials if available.
        const creds = await browser.runtime.sendMessage({
            action: 'page_get_submitted'
        });

        const redirectCount = await browser.runtime.sendMessage({
            action: 'page_get_redirect_count'
        });

        if (creds && creds.submitted) {
            // If username field is not set, wait for credentials in kpxc.retrieveCredentialsCallback.
            if (!creds.username) {
                return;
            }

            if (redirectCount >= kpxc.settings.redirectAllowance) {
                await browser.runtime.sendMessage({
                    action: 'page_clear_submitted'
                });
            }

            kpxc.rememberCredentials(creds.username, creds.password, creds.url, creds.oldCredentials);
        }
    } catch (err) {
        console.log('Error: Cannot load extension settings');
    }
};

if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll)) {
    initcb();
} else {
    document.addEventListener('DOMContentLoaded', initcb);
}

kpxc.init = function() {
    initcb();
};

// Detects DOM changes in the document
kpxc.initObserver = function() {
    const observer = new MutationObserver(function(mutations, obs) {
        if (document.visibilityState === 'hidden' || kpxcUI.mouseDown) {
            return;
        }

        // Limit the mutation handling
        if (mutations.length > _maximumMutations) {
            mutations.slice(0, _maximumMutations);
        }

        for (const mut of mutations) {
            // Skip text nodes
            if (mut.target.nodeType === Node.TEXT_NODE) {
                continue;
            }
    
            // Check document URL change and detect new fields
            kpxcObserverHelper.detectURLChange();
    
            // Handle attributes only if CSS display is modified
            if (mut.type === 'attributes') {
                // Check if some class is changed that folds a form or input field(s)
                if (mut.attributeName === 'class' && mut.target.querySelectorAll('form input').length > 0) {
                    kpxc.initCredentialFields(true);
                    continue;
                }
    
                const newValue = mut.target.getAttribute(mut.attributeName);
                if (newValue && (newValue.includes('display') || newValue.includes('z-index'))) {
                    if (mut.target.style.display !== 'none') {
                        kpxcObserverHelper.handleObserverAdd(mut.target);
                    } else {
                        kpxcObserverHelper.handleObserverRemove(mut.target);
                    }
                }
            } else if (mut.type === 'childList') {
                kpxcObserverHelper.handleObserverAdd((mut.addedNodes.length > 0) ? mut.addedNodes[0] : mut.target);
                kpxcObserverHelper.handleObserverRemove((mut.removedNodes.length > 0) ? mut.removedNodes[0] : mut.target);
            }
        }
    });
    
    // define what element should be observed by the observer
    // and what types of mutations trigger the callback
    observer.observe(document, {
        subtree: true,
        attributes: true,
        childList: true,
        characterData: true,
        attributeFilter: [ 'style', 'class' ]
    });
};

// Clears all from the content and background scripts, including autocomplete
kpxc.clearAllFromPage = function() {
    kpxcEvents.clearCredentials();
    browser.runtime.sendMessage({
        action: 'page_clear_logins'
    });

    // Switch back to default popup
    browser.runtime.sendMessage({
        action: 'get_status',
        args: [ true ] // Set polling to true, this is an internal function call
    });
};

// Switch credentials if database is changed or closed
kpxc.detectDatabaseChange = async function(response) {
    _databaseClosed = true;
    kpxc.clearAllFromPage();
    kpxc.switchIcons(true);

    if (document.visibilityState !== 'hidden') {
        if (response.new !== '' && response.new !== response.old) {
            _called.retrieveCredentials = false;
            const settings = await browser.runtime.sendMessage({
                action: 'load_settings'
            });
            kpxc.settings = settings;
            await kpxc.initCredentialFields(true);
            kpxc.switchIcons(false); // Unlocked
            _databaseClosed = false;

            // If user has requested a manual fill through context menu the actual credential filling
            // is handled here when the opened database has been regognized. It's not a pretty hack.
            if (_called.manualFillRequested && _called.manualFillRequested !== ManualFill.NONE) {
                await kpxc.fillInFromActiveElement(false, _called.manualFillRequested === ManualFill.PASS);
                _called.manualFillRequested = ManualFill.NONE;
            }
        }
    }
};

// Checks if the site has been ignored using Site Preferences
kpxc.siteIgnored = function(condition) {
    kpxc.initializeSitePreferences();
    if (kpxc.settings.sitePreferences) {
        let currentLocation;
        try {
            currentLocation = window.top.location.href;
        } catch (err) {
            // Cross-domain security error inspecting window.top.location.href.
            // This catches an error when an iframe is being accessed from another (sub)domain -> use the iframe URL instead.
            currentLocation = window.self.location.href;
        } 

        const currentSetting = condition || IGNORE_FULL;
        for (const site of kpxc.settings.sitePreferences) {
            if (siteMatch(site.url, currentLocation) || site.url === currentLocation) {
                if (site.ignore === currentSetting) {
                    return true;
                }

                _singleInputEnabledForPage = site.usernameOnly;
            }
        }
    }

    return false;
};

kpxc.initCredentialFields = async function(forceCall, inputs) {
    if (_called.initCredentialFields && !forceCall) {
        return;
    }
    _called.initCredentialFields = true;

    await browser.runtime.sendMessage({
        action: 'page_clear_logins',
        args: _called.clearLogins
    });

    _called.clearLogins = true;

    if (kpxc.siteIgnored()) {
        return;
    }

    // If target input fields are not defined, get inputs from the whole document
    if (inputs === undefined) {
        inputs = kpxcFields.getAllFields();
    }

    if (inputs.length === 0) {
        return;
    }

    // Update database closed status
    const res = await browser.runtime.sendMessage({
        action: 'get_status',
        args: [ true ]
    });
    _databaseClosed = res.databaseClosed;

    kpxcFields.prepareVisibleFieldsWithID('select');
    kpxc.initPasswordGenerator(inputs);

    if (kpxc.settings.showOTPIcon) {
        kpxc.initOTPFields(inputs);
    }

    if (!kpxcFields.useDefinedCredentialFields()) {
        // Get all combinations of username + password fields
        kpxcFields.combinations = kpxcFields.getAllCombinations(inputs);
    }
    kpxcFields.prepareCombinations(kpxcFields.combinations);

    if (kpxcFields.combinations.length === 0 && inputs.length === 0) {
        browser.runtime.sendMessage({
            action: 'show_default_browseraction'
        });
        return;
    }

    kpxc.url = document.location.origin;
    kpxc.submitUrl = kpxc.getFormActionUrl(kpxcFields.combinations[0]);

    // Get submitUrl for a single input
    if (!kpxc.submitUrl && kpxcFields.combinations.length === 1 && inputs.length === 1) {
        kpxc.submitUrl = kpxc.getFormActionUrlFromSingleInput(inputs[0]);
    }

    if (kpxc.settings.autoRetrieveCredentials && _called.retrieveCredentials === false && (kpxc.url && kpxc.submitUrl)) {
        _called.retrieveCredentials = true;
        kpxc.retrieveCredentialsCallback(await browser.runtime.sendMessage({
            action: 'retrieve_credentials',
            args: [ kpxc.url, kpxc.submitUrl ]
        }));
    } else if (_singleInputEnabledForPage) {
        kpxc.preparePageForMultipleCredentials(kpxc.credentials);
    }
};

kpxc.initPasswordGenerator = function(inputs) {
    if (!kpxc.settings.usePasswordGeneratorIcons) {
        return;
    }

    for (let i = 0; i < inputs.length; i++) {
        if (inputs[i] && inputs[i].getLowerCaseAttribute('type') === 'password') {
            kpxcPasswordIcons.newIcon(true, inputs[i], inputs, i, _databaseClosed);
        }
    }
};

kpxc.initOTPFields = function(inputs, databaseClosed) {
    for (const i of inputs) {
        const id = i.getLowerCaseAttribute('id');
        const name = i.getLowerCaseAttribute('name');
        const autocomplete = i.getLowerCaseAttribute('autocomplete');

        if (autocomplete === 'one-time-code' || acceptedOTPFields.some(f => (id && id.includes(f)) || (name && name.includes(f)))) {
            kpxcTOTPIcons.newIcon(i, _databaseClosed);
        }
    }
};

kpxc.receiveCredentialsIfNecessary = async function() {
    if (kpxc.credentials.length === 0 && _called.retrieveCredentials === false) {
        const credentials = await browser.runtime.sendMessage({
            action: 'retrieve_credentials',
            args: [ kpxc.url, kpxc.submitUrl, true ] // Sets triggerUnlock to true
        });

        // If the database was locked, this is scope never met. In these cases the response is met at kpxc.detectDatabaseChange
        _called.manualFillRequested = ManualFill.NONE;
        await kpxc.retrieveCredentialsCallback(credentials, false);
        return credentials;
    }

    return kpxc.credentials;
};

kpxc.retrieveCredentialsCallback = async function(credentials, dontAutoFillIn) {
    if (kpxcFields.combinations.length > 0) {
        kpxc.u = _f(kpxcFields.combinations[0].username);
        kpxc.p = _f(kpxcFields.combinations[0].password);
    }

    if (credentials && credentials.length > 0) {
        kpxc.credentials = credentials;
        kpxc.prepareFieldsForCredentials(!dontAutoFillIn);
    }

    // Retrieve submitted credentials if available
    const creds = await browser.runtime.sendMessage({
        action: 'page_get_submitted'
    });

    if (creds && creds.submitted) {
        await browser.runtime.sendMessage({
            action: 'page_clear_submitted'
        });

        kpxc.rememberCredentials(creds.username, creds.password, creds.url, creds.oldCredentials);
    }
};

kpxc.prepareFieldsForCredentials = function(autoFillInForSingle) {
    // Only one login for this site
    if (autoFillInForSingle && kpxc.settings.autoFillSingleEntry && kpxc.credentials.length === 1) {
        let combination = null;
        if (!kpxc.p && !kpxc.u && kpxcFields.combinations.length > 0) {
            kpxc.u = _f(kpxcFields.combinations[0].username);
            kpxc.p = _f(kpxcFields.combinations[0].password);
            combination = kpxcFields.combinations[0];
        }
        if (kpxc.u) {
            kpxc.setValueWithChange(kpxc.u, kpxc.credentials[0].login);
            combination = kpxcFields.getCombination('username', kpxc.u);
        }
        if (kpxc.p) {
            kpxc.setValueWithChange(kpxc.p, kpxc.credentials[0].password);
            combination = kpxcFields.getCombination('password', kpxc.p);
        }

        if (combination) {
            let list = [];
            if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[0].stringFields, list)) {
                kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
            }
        }

        // Generate popup-list of usernames + descriptions
        browser.runtime.sendMessage({
            action: 'popup_login',
            args: [ `${kpxc.credentials[0].login} (${kpxc.credentials[0].name})` ]
        });
    } else if (kpxc.credentials.length > 1 || (kpxc.credentials.length > 0 && (!kpxc.settings.autoFillSingleEntry || !autoFillInForSingle))) {
        kpxc.preparePageForMultipleCredentials(kpxc.credentials);
    }
};

kpxc.preparePageForMultipleCredentials = function(credentials) {
    if (credentials.length === 0) {
        return;
    }

    function getLoginText(credential, withGroup) {
        const group = (withGroup && credential.group) ? `[${credential.group}] ` : '';
        const visibleLogin = (credential.login.length > 0) ? credential.login : tr('credentialsNoUsername');
        const text = `${group}${credential.name} (${visibleLogin})`;
        if (credential.expired && credential.expired === 'true') {
            return `${text} [${tr('credentialExpired')}]`;
        }
        return text;
    }

    function getUniqueGroupCount(credentials) {
        const groups = credentials.map(c => c.group || '')
        const uniqueGroups = new Set(groups)
        return uniqueGroups.size
    }

    // Add usernames + descriptions to autocomplete-list and popup-list
    const usernames = [];
    kpxcAutocomplete.elements = [];
    const showGroupNameInAutocomplete = kpxc.settings.showGroupNameInAutocomplete && (getUniqueGroupCount(credentials) > 1)
    for (let i = 0; i < credentials.length; i++) {
        const loginText = getLoginText(credentials[i], showGroupNameInAutocomplete);
        usernames.push(loginText);

        const item = {
            label: loginText,
            value: credentials[i].login,
            loginId: i
        };
        kpxcAutocomplete.elements.push(item);
    }

    // Generate popup-list of usernames + descriptions
    browser.runtime.sendMessage({
        action: 'popup_login',
        args: usernames
    });

    // Initialize autocomplete for username fields
    if (kpxc.settings.autoCompleteUsernames) {
        for (const i of kpxcFields.combinations) {
            // Both username and password fields are visible
            if (_detectedFields >= 2) {
                if (_f(i.username)) {
                    kpxcAutocomplete.create(_f(i.username), false, kpxc.settings.autoSubmit);
                }
            } else if (_detectedFields === 1) {
                if (_f(i.username)) {
                    kpxcAutocomplete.create(_f(i.username), false, kpxc.settings.autoSubmit);
                }
                if (_f(i.password)) {
                    kpxcAutocomplete.create(_f(i.password), false, kpxc.settings.autoSubmit);
                }
            }
        }
    }
};

// Returns the form that includes the inputField
kpxc.getForm = function(inputField) {
    for (const f of document.forms) {
        for (const e of f.elements) {
            if (e === inputField) {
                return f;
            }
        }
    }
};

kpxc.getFormActionUrl = function(combination) {
    if (!combination) {
        return null;
    }

    const field = _f(combination.password) || _f(combination.username);
    if (field === null) {
        return null;
    }

    const form = kpxc.getForm(field);
    let action = null;

    if (form && form.length > 0) {
        action = form.action;
    }

    if (typeof(action) !== 'string' || action === '') {
        action = document.location.origin + document.location.pathname;
    }

    return action;
};

kpxc.getFormActionUrlFromSingleInput = function(field) {
    if (!field) {
        return null;
    }

    let action = field.formAction;

    if (typeof(action) !== 'string' || action === '') {
        action = document.location.origin + document.location.pathname;
    }

    return action;
};

// Get the form submit button instead if action URL is same as the page itself
kpxc.getFormSubmitButton = function(form) {
    const action = kpxc.submitUrl || form.action;
    if (action.includes(document.location.origin + document.location.pathname)) {
        for (const i of form.elements) {
            if (i.type === 'submit') {
                return i;
            }
        }
    }

    // Try to find another button. Select the first one.
    const buttons = Array.from(form.querySelectorAll('button[type=\'button\'], button[type=\'submit\'], input[type=\'button\'], button:not([type])'));
    if (buttons.length > 0) {
        return buttons[0];
    }

    return undefined;
};

kpxc.fillInCredentials = async function(combination, onlyPassword, suppressWarnings) {
    const action = kpxc.getFormActionUrl(combination);
    const u = _f(combination.username);
    const p = _f(combination.password);

    if (combination.isNew) {
        // Initialize form-submit for remembering credentials
        const fieldId = combination.password || combination.username;
        const field = _f(fieldId);
        if (field) {
            const form = kpxc.getForm(field);
            if (form && form.length > 0) {
                kpxcForm.init(form, combination);
            }
        }
    }

    if (u) {
        kpxc.u = u;
    }
    if (p) {
        kpxc.p = p;
    }

    if (kpxc.url === document.location.origin && kpxc.submitUrl === action && kpxc.credentials.length > 0) {
        kpxc.fillIn(combination, onlyPassword, suppressWarnings);
    } else {
        kpxc.url = document.location.origin;
        kpxc.submitUrl = action;

        const credentials = await browser.runtime.sendMessage({
            action: 'retrieve_credentials',
            args: [ kpxc.url, kpxc.submitUrl, true ] // Sets triggerUnlock to true
        });

        await kpxc.retrieveCredentialsCallback(credentials, true);
        kpxc.fillIn(combination, onlyPassword, suppressWarnings);
    }
};

kpxc.fillInFromActiveElement = function(suppressWarnings, passOnly = false) {
    const el = document.activeElement;
    if (el.tagName.toLowerCase() !== 'input') {
        if (kpxcFields.combinations.length > 0) {
            kpxc.fillInCredentials(kpxcFields.combinations[0], passOnly, suppressWarnings);

            // Focus to the input field
            const field = _f(passOnly ? kpxcFields.combinations[0].password : kpxcFields.combinations[0].username);
            if (field) {
                field.focus();
            }
        }
        return;
    }

    kpxcFields.setUniqueId(el);
    const fieldId = kpxcFields.prepareId(el.getAttribute('data-kpxc-id'));
    let combination = null;
    if (el.getAttribute('type') === 'password') {
        combination = kpxcFields.getCombination('password', fieldId);
    } else {
        combination = kpxcFields.getCombination('username', fieldId);
    }

    if (passOnly) {
        if (!_f(combination.password)) {
            kpxcUI.createNotification('warning', tr('fieldsNoPasswordField'));
            return;
        }
    }

    delete combination.loginId;

    kpxc.fillInCredentials(combination, passOnly, suppressWarnings);
};

kpxc.fillInFromActiveElementTOTPOnly = async function(target) {
    const el = target || document.activeElement;
    kpxcFields.setUniqueId(el);
    const fieldId = kpxcFields.prepareId(el.getAttribute('data-kpxc-id'));

    const index = await browser.runtime.sendMessage({
        action: 'page_get_login_id'
    });

    if (index >= 0 && kpxc.credentials[index]) {
        // Check the value from stringFields (to be removed)
        const currentField = _fs(fieldId);
        if (kpxc.credentials[index].stringFields && kpxc.credentials[index].stringFields.length > 0) {
            const stringFields = kpxc.credentials[index].stringFields;
            for (const s of stringFields) {
                const val = s['KPH: {TOTP}'];
                if (val) {
                    kpxc.setValue(currentField, val);
                }
            }
        } else if (kpxc.credentials[index].totp && kpxc.credentials[index].totp.length > 0) {
            kpxc.setValue(currentField, kpxc.credentials[index].totp);
        }
    }
};

kpxc.setValue = function(field, value) {
    if (field.matches('select')) {
        value = value.toLowerCase().trim();
        const options = field.querySelectorAll('option');
        for (const o of options) {
            if (o.textContent.toLowerCase().trim() === value) {
                kpxc.setValueWithChange(field, o.value);
                return false;
            }
        }
    } else {
        kpxc.setValueWithChange(field, value);
    }
};

kpxc.fillInStringFields = function(fields, stringFields, filledInFields) {
    let filledIn = false;

    filledInFields.list = [];
    if (fields && stringFields && fields.length > 0 && stringFields.length > 0) {
        for (let i = 0; i < fields.length; i++) {
            const currentField = _fs(fields[i]);
            const stringFieldValue = Object.values(stringFields[i]);
            if (currentField && stringFieldValue[0]) {
                kpxc.setValue(currentField, stringFieldValue[0]);
                filledInFields.list.push(fields[i]);
                filledIn = true;
            }
        }
    }

    return filledIn;
};

kpxc.setValueWithChange = function(field, value) {
    if (kpxc.settings.respectMaxLength === true) {
        const attributeMaxlength = field.getAttribute('maxlength');
        if (attributeMaxlength && !isNaN(attributeMaxlength) && attributeMaxlength > 0) {
            value = value.substr(0, attributeMaxlength);
        }
    }

    field.value = value;
    field.dispatchEvent(new Event('input', { 'bubbles': true }));
    field.dispatchEvent(new Event('change', { 'bubbles': true }));
};

kpxc.fillWithSpecificLogin = function(id) {
    if (kpxc.credentials[id]) {
        let combination = null;
        if (kpxc.u) {
            kpxc.setValueWithChange(kpxc.u, kpxc.credentials[id].login);
            combination = kpxcFields.getCombination('username', kpxc.u);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: id
            });
            kpxc.u.focus();
        }
        if (kpxc.p) {
            kpxc.setValueWithChange(kpxc.p, kpxc.credentials[id].password);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: id
            });
            combination = kpxcFields.getCombination('password', kpxc.p);
        }

        let list = [];
        if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[id].stringFields, list)) {
            kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
        }

        kpxcAutocomplete.closeList();
    }
};

kpxc.fillIn = function(combination, onlyPassword, suppressWarnings) {
    // No credentials available
    if (kpxc.credentials.length === 0 && !suppressWarnings) {
        kpxcUI.createNotification('error', tr('credentialsNoLoginsFound'));
        return;
    }

    let skipAutoSubmit = false;
    const uField = _f(combination.username);
    const pField = _f(combination.password);

    // Exactly one pair of credentials available
    if (kpxc.credentials.length === 1) {
        let filledIn = false;

        if (kpxc.credentials[0].skipAutoSubmit !== undefined) {
            skipAutoSubmit = kpxc.credentials[0].skipAutoSubmit === 'true';
        }

        if (uField && (!onlyPassword || _singleInputEnabledForPage)) {
            kpxc.setValueWithChange(uField, kpxc.credentials[0].login);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: 0
            });
            filledIn = true;
        }
        if (pField) {
            pField.setAttribute('type', 'password');
            kpxc.setValueWithChange(pField, kpxc.credentials[0].password);
            pField.setAttribute('unchanged', true);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: 0
            });
            filledIn = true;
            kpxc.setPasswordFilled(true);
        }

        let list = [];
        if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[0].stringFields, list)) {
            kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
            filledIn = true;
        }

        if (!filledIn) {
            if (!suppressWarnings) {
                kpxcUI.createNotification('error', tr('fieldsFill'));
            }
            return;
        }
    } else if (combination.loginId !== undefined && kpxc.credentials[combination.loginId]) {
        // Specific login ID given
        let filledIn = false;

        if (kpxc.credentials[0].skipAutoSubmit !== undefined) {
            skipAutoSubmit = kpxc.credentials[combination.loginId].skipAutoSubmit === 'true';
        }

        if (uField && (!onlyPassword || _singleInputEnabledForPage)) {
            kpxc.setValueWithChange(uField, kpxc.credentials[combination.loginId].login);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: combination.loginId
            });
            filledIn = true;
        }

        if (pField) {
            kpxc.setValueWithChange(pField, kpxc.credentials[combination.loginId].password);
            pField.setAttribute('unchanged', true);
            browser.runtime.sendMessage({
                action: 'page_set_login_id', args: combination.loginId
            });
            filledIn = true;
            kpxc.setPasswordFilled(true);
        }

        let list = [];
        if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[combination.loginId].stringFields, list)) {
            kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
            filledIn = true;
        }

        if (!filledIn) {
            if (!suppressWarnings) {
                kpxcUI.createNotification('error', tr('fieldsFill'));
            }
            return;
        }
    } else { // Multiple credentials available
        // Check if only one password for given username exists
        let countPasswords = 0;

        if (uField) {
            let valPassword = '';
            let valUsername = '';
            let valStringFields = [];
            const valQueryUsername = uField.value.toLowerCase();

            // Find passwords to given username (even those with empty username)
            for (const c of kpxc.credentials) {
                if (c.login.toLowerCase() === valQueryUsername) {
                    countPasswords += 1;
                    valPassword = c.password;
                    valUsername = c.login;
                    valStringFields = c.stringFields;

                    if (c.skipAutoSubmit !== undefined) {
                        skipAutoSubmit = c.skipAutoSubmit === 'true';
                    }
                }
            }

            // For the correct notification message: 0 = no logins, X > 1 = too many logins
            if (countPasswords === 0) {
                countPasswords = kpxc.credentials.length;
            }

            // Only one mapping username found
            if (countPasswords === 1) {
                if (!onlyPassword) {
                    kpxc.setValueWithChange(uField, valUsername);
                }

                if (pField) {
                    kpxc.setValueWithChange(pField, valPassword);
                    pField.setAttribute('unchanged', true);
                    kpxc.setPasswordFilled(true);
                }

                let list = [];
                if (kpxc.fillInStringFields(combination.fields, valStringFields, list)) {
                    kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
                }
            }

            // User has to select correct credentials by himself
            if (countPasswords > 1) {
                if (!suppressWarnings) {
                    const target = onlyPassword ? pField : uField;
                    if (!target) {
                        return;
                    }

                    if (kpxcAutocomplete.started) {
                        kpxcAutocomplete.showList(target);
                    } else {
                        kpxcAutocomplete.create(target, true, kpxc.settings.autoSubmit);
                    }
                    target.focus();
                }
                return;
            } else if (countPasswords < 1) {
                if (!suppressWarnings) {
                    kpxcUI.createNotification('error', tr('credentialsNoUsernameFound'));
                }
                return;
            }
        } else {
            if (!suppressWarnings) {
                const target = onlyPassword ? pField : uField;
                if (!target) {
                    return;
                }

                if (kpxcAutocomplete.started) {
                    kpxcAutocomplete.showList(target);
                } else {
                    kpxcAutocomplete.create(target, true, kpxc.settings.autoSubmit);
                }
                target.focus();
                return;
            }
        }
    }

    // Close autocomplete menu after fill
    kpxcAutocomplete.closeList();

    // Auto-submit
    if (kpxc.settings.autoSubmit && !skipAutoSubmit) {
        const form = kpxc.u.form || kpxc.p.form;
        const submitButton = kpxc.getFormSubmitButton(form);
        if (submitButton !== undefined) {
            submitButton.click();
        } else {
            form.submit();
        }
    }
};

kpxc.contextMenuRememberCredentials = async function() {
    const el = document.activeElement;
    if (el.tagName.toLowerCase() !== 'input') {
        return;
    }

    kpxcFields.setUniqueId(el);
    const fieldId = kpxcFields.prepareId(el.getAttribute('data-kpxc-id'));
    let combination = null;
    if (el.getAttribute('type') === 'password') {
        combination = kpxcFields.getCombination('password', fieldId);
    } else {
        combination = kpxcFields.getCombination('username', fieldId);
    }

    let usernameValue = '';
    let passwordValue = '';

    const usernameField = _f(combination.username);
    const passwordField = _f(combination.password);

    if (usernameField) {
        usernameValue = usernameField.value;
    }

    if (passwordField) {
        passwordValue = passwordField.value;
    }

    const result = await kpxc.rememberCredentials(usernameValue, passwordValue);
    if (result === undefined) {
        kpxcUI.createNotification('error', tr('rememberNoPassword'));
        return;
    }

    if (!result) {
        kpxcUI.createNotification('warning', tr('rememberCredentialsExists'));
    }
};

/**
 * Gets the credential list and shows the update banner
 * @param {string} usernameValue    Submitted username
 * @param {string} passwordValue    Submitted password
 * @param {string} urlValue         URL of the page where password change was detected
 * @param {Array} oldCredentials    Credentials saved from the password change page, if available
 */
kpxc.rememberCredentials = async function(usernameValue, passwordValue, urlValue, oldCredentials) {
    const credentials = (oldCredentials !== undefined && oldCredentials.length > 0) ? oldCredentials : kpxc.credentials;

    // No password given or field cleaned by a site-running script
    // --> no password to save
    if (passwordValue === '') {
        return undefined;
    }

    let usernameExists = false;
    let nothingChanged = false;

    for (const c of credentials) {
        if (c.login === usernameValue && c.password === passwordValue) {
            nothingChanged = true;
            break;
        }

        if (c.login === usernameValue) {
            usernameExists = true;
        }
    }

    if (!nothingChanged) {
        if (!usernameExists) {
            for (const c of credentials) {
                if (c.login === usernameValue) {
                    usernameExists = true;
                    break;
                }
            }
        }
        const credentialsList = [];
        for (const c of credentials) {
            credentialsList.push({
                login: c.login,
                name: c.name,
                uuid: c.uuid
            });
        }

        let url = this.action;
        if (!url) {
            url = kpxc.settings.saveDomainOnlyNewCreds ? document.location.origin : document.location.href;
            if (url.indexOf('?') > 0) {
                url = url.substring(0, url.indexOf('?'));
                if (url.length < document.location.origin.length) {
                    url = document.location.origin;
                }
            }
        }

        urlValue = urlValue || url;

        // Set usernameValue to the first one in the list, or the selected entry
        if (usernameValue === '') {
            if (credentialsList.length === 1) {
                usernameValue = credentialsList[0].login;
            } else if (credentialsList.length > 1) {
                const index = await browser.runtime.sendMessage({
                    action: 'page_get_login_id'
                });

                if (index >= 0) {
                    usernameValue = credentialsList[index].login;
                }
            }
        }

        // Show the banner
        const newCredentials = {
            username: usernameValue,
            password: passwordValue,
            url: urlValue,
            usernameExists: usernameExists,
            list: credentialsList
        };

        kpxcBanner.create(newCredentials);
        return true;
    }

    return false;
};

kpxc.getSite = function(sites) {
    if (!sites || sites.length === 0) {
        return '';
    }

    let site = trimURL(sites[0]);
    kpxc.initializeSitePreferences();

    if (slashNeededForUrl(site)) {
        site += '/';
    }

    return site;
};

kpxc.ignoreSite = async function(sites) {
    const site = kpxc.getSite(sites);

    // Check if the site already exists
    let siteExists = false;
    for (const existingSite of kpxc.settings['sitePreferences']) {
        if (existingSite.url === site) {
            existingSite.ignore = IGNORE_NORMAL;
            siteExists = true;
        }
    }

    if (!siteExists) {
        kpxc.settings['sitePreferences'].push({
            url: site,
            ignore: IGNORE_NORMAL,
            usernameOnly: false
        });
    }

    await browser.runtime.sendMessage({
        action: 'save_settings',
        args: [ kpxc.settings ]
    });
};

kpxc.addToSitePreferences = async function(sites) {
    kpxc.initializeSitePreferences();

    // Returns a predefined URL for certain sites
    const site = kpxcSites.definedURL(trimURL(window.top.location.href));

    // Check if the site already exists -> update the current settings
    let siteExists = false;
    for (const existingSite of kpxc.settings['sitePreferences']) {
        if (existingSite.url === site) {
            existingSite.ignore = IGNORE_NOTHING;
            existingSite.usernameOnly = true;
            siteExists = true;
        }
    }

    if (!siteExists) {
        kpxc.settings['sitePreferences'].push({
            url: site,
            ignore: IGNORE_NOTHING,
            usernameOnly: true
        });
    }

    await browser.runtime.sendMessage({
        action: 'save_settings',
        args: [ kpxc.settings ]
    });

    browser.runtime.sendMessage({
        action: 'username_field_detected',
        args: false
    });
};

// Delete previously created Object if it exists. It will be replaced by an Array
kpxc.initializeSitePreferences = function() {
    if (kpxc.settings['sitePreferences'] !== undefined && kpxc.settings['sitePreferences'].constructor === Object) {
        delete kpxc.settings['sitePreferences'];
    }

    if (!kpxc.settings['sitePreferences']) {
        kpxc.settings['sitePreferences'] = [];
    }
};

kpxc.getDocumentLocation = function() {
    return kpxc.settings.saveDomainOnly ? document.location.origin : document.location.href;
};

// Sets the icons to corresponding database lock status
kpxc.switchIcons = function(locked) {
    kpxcUsernameIcons.switchIcon(locked);
    kpxcPasswordIcons.switchIcon(locked);
    kpxcTOTPIcons.switchIcon(locked);
};

kpxc.setPasswordFilled = function(state) {
    browser.runtime.sendMessage({
        action: 'password_set_filled',
        args: state
    });
};

kpxc.passwordFilled = async function() {
    return await browser.runtime.sendMessage({ action: 'password_get_filled' });
};


const kpxcEvents = {};

kpxcEvents.clearCredentials = function() {
    kpxc.credentials = [];
    kpxcAutocomplete.elements = [];
    _called.retrieveCredentials = false;

    if (kpxc.settings.autoCompleteUsernames) {
        for (const c of kpxcFields.combinations) {
            const uField = _f(c.username);
            if (uField) {
                if (uField.classList.contains('ui-autocomplete-input')) {
                    uField.autocomplete('destroy');
                }
            }
        }
    }
};

kpxcEvents.triggerActivatedTab = async function() {
    // Doesn't run a second time because of _called.initCredentialFields set to true
    kpxc.init();

    // Update username field lock state
    const state = await browser.runtime.sendMessage({ action: 'check_database_hash' });
    kpxc.switchIcons(state === '');

    // initCredentialFields calls also "retrieve_credentials", to prevent it
    // check of init() was already called
    if (_called.initCredentialFields && (kpxc.url && kpxc.submitUrl) && kpxc.settings.autoRetrieveCredentials) {
        _called.retrieveCredentials = true;
        kpxc.retrieveCredentialsCallback(await browser.runtime.sendMessage({
            action: 'retrieve_credentials',
            args: [ kpxc.url, kpxc.submitUrl ]
        }));
    }
};