-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1963 lines (1686 loc) · 61.3 KB
/
content.js
File metadata and controls
1963 lines (1686 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Content Script for AutoFill Plugin
* Kjører på alle websider og håndterer felt-deteksjon og autofill
*/
// Hindre dobbel-injeksjon (kan skje ved register + manifest)
if (window.__autofillContentLoaded) {
console.debug('[AutoFill] Content script already loaded, skipping re-init.');
} else {
window.__autofillContentLoaded = true;
// Globale variabler
let lastClickedElement = null;
let autoFillRules = [];
let executedMacros = new Set(); // Ny: Hindre loop ved makro-avspilling
let debugMode = false;
let autofillEnabled = true;
let autofillDelayMs = 0;
let autofillTrigger = 'auto'; // auto | interaction
let blacklist = [];
let whitelist = [];
let fieldBlacklist = []; // Ny
// ENDRING: Ny variabel for varslinger
let notificationsEnabled = true;
let scanToastEnabled = true; // Ny: Vis scan-toast i hjørnet
let userVariables = {};
let currentLanguage = 'en';
let currentProfileId = 'default';
// Observer references for cleanup (prevents memory leaks)
let domObserver = null;
let modalObserver = null;
// Regex compilation cache (prevents re-creating regex objects on every match)
const regexCache = new Map();
const REGEX_CACHE_MAX_SIZE = 100;
/**
* Debounce utility - delays function execution until after wait ms have elapsed
* since the last time it was invoked
* @param {Function} func - Function to debounce
* @param {number} wait - Milliseconds to wait
* @returns {Function} - Debounced function
*/
function debounce(func, wait) {
let timeout = null;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// Debounced version of triggerAutoFill for high-frequency events
const debouncedTriggerAutoFill = debounce(() => triggerAutoFill(), 150);
/**
* Get or create a cached regex object
* @param {string} pattern - The regex pattern
* @param {string} flags - Regex flags (default 'i' for case-insensitive)
* @returns {RegExp|null} - Compiled regex or null if invalid
*/
function getCachedRegex(pattern, flags = 'i') {
const cacheKey = `${pattern}::${flags}`;
if (regexCache.has(cacheKey)) {
return regexCache.get(cacheKey);
}
try {
const regex = new RegExp(pattern, flags);
// Evict oldest entries if cache is full
if (regexCache.size >= REGEX_CACHE_MAX_SIZE) {
const firstKey = regexCache.keys().next().value;
regexCache.delete(firstKey);
}
regexCache.set(cacheKey, regex);
return regex;
} catch (error) {
console.error('Invalid regex pattern:', pattern, error);
regexCache.set(cacheKey, null); // Cache the failure too
return null;
}
}
/**
* Initialiser content script
* Wrapped i try-catch for robust feilhåndtering
*/
(async function init() {
try {
debugLog('AutoFill Plugin content script lastet');
// Last inn innstillinger (med fallback ved feil)
await loadSettings().catch(err => {
console.warn('[AutoFill] Failed to load settings, using defaults:', err);
});
await loadCurrentProfile().catch(err => {
console.warn('[AutoFill] Failed to load profile, using default:', err);
});
const loc = getEffectiveLocation();
// Sjekk blacklist/whitelist før vi gjør noe som helst (inkludert scanning)
if (isBlockedSite(loc.hostname, loc.href)) {
debugLog('Site blokkert av blacklist/whitelist, stopper init');
return;
}
// Hent regler for denne siden
await loadRulesForCurrentSite(currentProfileId).catch(err => {
console.warn('[AutoFill] Failed to load rules:', err);
});
// Lytt til focus-events for å spore siste klikket element
document.addEventListener('mousedown', handleMouseDown, true);
// Kjor autofill når siden er ferdig lastet (hvis aktivert)
if (autofillEnabled) {
if (autofillTrigger === 'interaction') {
attachInteractionTrigger();
} else {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', triggerAutoFill);
} else {
triggerAutoFill();
}
}
}
// Observer DOM-endringer for dynamiske sider (SPA)
observeDOMChanges();
// Observer modals som åpnes
observeModalChanges();
// Fang høyreklikk slik at context menu-lagring alltid har et felt
document.addEventListener('contextmenu', handleMouseDown, true);
} catch (error) {
console.error('[AutoFill] Critical initialization error:', error);
}
})();
// --- MACRO RECORDER & PLAYER START ---
const MacroRecorder = {
isRecording: false,
startTime: 0,
steps: [],
overlay: null,
lastEventTime: 0,
start: function() {
if (this.isRecording) return;
this.isRecording = true;
this.startTime = Date.now();
this.lastEventTime = this.startTime;
this.steps = [];
this.createOverlay();
// Attach listeners
document.addEventListener('click', this.handleClick, true);
document.addEventListener('change', this.handleChange, true);
document.addEventListener('keydown', this.handleKeydown, true);
debugLog('Macro recording started');
},
stop: function() {
if (!this.isRecording) return;
this.isRecording = false;
this.removeOverlay();
// Remove listeners
document.removeEventListener('click', this.handleClick, true);
document.removeEventListener('change', this.handleChange, true);
document.removeEventListener('keydown', this.handleKeydown, true);
debugLog('Macro recording stopped', this.steps);
return this.steps;
},
recordStep: function(type, target, value = null, extra = {}) {
const now = Date.now();
const delay = now - this.lastEventTime;
this.lastEventTime = now;
const selector = generateSelector(target);
if (!selector && target !== document.body) {
console.warn('Could not generate selector for', target);
return;
}
const step = {
type: type,
selector: selector,
delay: delay, // Delay før denne handlingen utføres
...extra
};
if (value !== null) step.value = value;
this.steps.push(step);
this.updateOverlayCount();
},
handleClick: function(e) {
// Ikke ta opp klikk på vår egen overlay
if (MacroRecorder.overlay && MacroRecorder.overlay.contains(e.target)) return;
// Unngå doble klikk-registreringer (debounce)
const lastStep = this.steps[this.steps.length - 1];
const now = Date.now();
if (lastStep && lastStep.type === 'click' && (now - this.lastEventTime < 500)) {
// Sjekk om det er samme element (via selector)
const currentSelector = generateSelector(e.target);
if (lastStep.selector === currentSelector) {
debugLog('Ignorerer dobbeltklikk i opptak');
return;
}
}
MacroRecorder.recordStep('click', e.target);
},
handleChange: function(e) {
// Registrer endringer i input felt
const val = getFieldValue(e.target);
MacroRecorder.recordStep('type', e.target, val);
},
handleKeydown: function(e) {
// Vi bryr oss primært om navigasjonstaster som Enter, Tab, piler
const importantKeys = ['Enter', 'Tab', 'ArrowDown', 'ArrowUp', 'Escape'];
if (importantKeys.includes(e.key)) {
MacroRecorder.recordStep('key', e.target, null, { key: e.key, code: e.code });
}
},
createOverlay: function() {
if (!document.body) return; // Cannot create overlay without body
const div = document.createElement('div');
if (!div.style) return; // Safety check
div.id = 'autofill-recorder-overlay';
div.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
background: #ef4444;
color: white;
padding: 12px 20px;
border-radius: 8px;
font-family: sans-serif;
font-size: 14px;
font-weight: bold;
z-index: 999999;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
display: flex;
align-items: center;
gap: 10px;
cursor: default;
`;
div.innerHTML = `
<span>🔴 Recording... <span id="af-rec-count">(0)</span></span>
<button id="af-rec-stop" style="
background: white;
color: #ef4444;
border: none;
padding: 4px 8px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
">Stop & Save</button>
`;
document.body.appendChild(div);
this.overlay = div;
document.getElementById('af-rec-stop').addEventListener('click', () => {
const macro = this.stop();
// Send macro til background for lagring
const host = window.location.hostname;
chrome.runtime.sendMessage({
action: 'addRule',
rule: {
sitePattern: host,
siteMatchType: 'host',
fieldType: 'macro', // Ny type
fieldPattern: 'Macro: ' + new Date().toLocaleString(),
value: JSON.stringify(macro), // Lagre stegene som JSON-streng
priority: 100
}
}, () => {
alert('Macro saved! Reload page to test.');
});
});
},
updateOverlayCount: function() {
const el = document.getElementById('af-rec-count');
if (el) el.textContent = `(${this.steps.length})`;
},
removeOverlay: function() {
if (this.overlay) {
this.overlay.remove();
this.overlay = null;
}
},
// Sørg for at context (this) er riktig i event handlers
bind: function() {
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleKeydown = this.handleKeydown.bind(this);
}
};
MacroRecorder.bind();
const MacroPlayer = {
play: async function(macroJson) {
let steps;
try {
steps = typeof macroJson === 'string' ? JSON.parse(macroJson) : macroJson;
} catch (e) {
console.error('Invalid macro JSON', e);
return;
}
if (!Array.isArray(steps)) return;
console.log('[AutoFill Macro] Starting playback with', steps.length, 'steps'); // Forced log
for (const step of steps) {
// Vent angitt delay (eller default 300ms for stabilitet)
const delay = Math.max(step.delay || 300, 100);
await new Promise(r => setTimeout(r, delay));
const el = document.querySelector(step.selector);
if (!el) {
debugLog('Macro element not found:', step.selector, 'Skipping step');
continue;
}
debugLog('Executing step:', step.type, step.selector);
try {
// Sørg for at elementet er synlig og klart
el.scrollIntoView({ block: 'center', inline: 'center' });
if (step.type === 'click') {
// Simuler full klikk-sekvens
el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
el.click();
} else if (step.type === 'type') {
el.focus();
setNativeValue(el, processValue(step.value)); // Støtt variabler i makroer også!
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
// Blur er ofte lurt etter typing
// el.blur();
} else if (step.type === 'key') {
el.dispatchEvent(new KeyboardEvent('keydown', { key: step.key, code: step.code, bubbles: true }));
el.dispatchEvent(new KeyboardEvent('keyup', { key: step.key, code: step.code, bubbles: true }));
// Spesialhåndtering: Hvis det er Enter på en form, kan det hende vi skal submitte?
// Nei, la siden håndtere det.
}
} catch (err) {
console.error('Error executing macro step', step, err);
}
}
debugLog('Macro playback finished');
}
};
// --- MACRO RECORDER & PLAYER END ---
/**
* Last inn innstillinger fra sync storage (synkroniseres mellom Chrome-profiler)
*/
async function loadSettings() {
try {
// Settings are stored in sync storage, profile-specific data in local
const syncKeys = ['debugMode', 'autofillEnabled', 'autofillDelay', 'autofillTrigger', 'blacklist', 'whitelist', 'notificationsEnabled', 'scanToastEnabled', 'userVariables', 'language', 'fieldBlacklist'];
const localKeys = ['currentProfileId'];
let syncResult = {};
try {
syncResult = await chrome.storage.sync.get(syncKeys);
} catch (e) {
// Fallback to local if sync fails
syncResult = await chrome.storage.local.get(syncKeys);
}
const localResult = await chrome.storage.local.get(localKeys);
debugMode = syncResult.debugMode || false;
autofillEnabled = syncResult.autofillEnabled !== false; // Default true
autofillDelayMs = parseInt(syncResult.autofillDelay) || 0;
autofillTrigger = syncResult.autofillTrigger || 'auto';
blacklist = Array.isArray(syncResult.blacklist) ? syncResult.blacklist : [];
whitelist = Array.isArray(syncResult.whitelist) ? syncResult.whitelist : [];
fieldBlacklist = Array.isArray(syncResult.fieldBlacklist) ? syncResult.fieldBlacklist : [];
notificationsEnabled = syncResult.notificationsEnabled !== false; // Default true
scanToastEnabled = syncResult.scanToastEnabled !== false; // Default true
userVariables = syncResult.userVariables || {};
currentLanguage = syncResult.language || 'en';
if (localResult.currentProfileId) {
currentProfileId = localResult.currentProfileId;
}
debugLog('Innstillinger lastet:', { debugMode, autofillEnabled, autofillDelayMs, autofillTrigger, blacklist, whitelist, fieldBlacklist, notificationsEnabled, scanToastEnabled, userVariables, currentLanguage });
} catch (error) {
console.error('Error loading settings:', error);
}
}
/**
* Debug logging - kun når debug mode er på
*/
function debugLog(...args) {
if (debugMode) {
console.log('[AutoFill Debug]', ...args);
}
}
/**
* Sjekk blacklist/whitelist for gjeldende site
*
* Støtter følgende mønstre:
* - "facebook.com" → matcher facebook.com OG *.facebook.com (smart domene-matching)
* - "*.facebook.com" → matcher kun subdomener (www.facebook.com, m.facebook.com)
* - "regex:pattern" → matcher med regex
* - "example.com/path*" → matcher URL med wildcard
*/
function isBlockedSite(hostname, url) {
const matchesAnyPattern = (patterns, hostname, fullUrl) => {
return patterns.some(pattern => {
pattern = pattern.trim();
if (!pattern) return false;
// Regex-mønster (prefiks "regex:")
if (pattern.startsWith('regex:')) {
try {
const regex = new RegExp(pattern.slice(6), 'i');
return regex.test(hostname) || regex.test(fullUrl);
} catch (e) {
return false;
}
}
// Eksakt match
if (hostname === pattern || fullUrl === pattern) return true;
// Wildcard-mønster (inneholder * eller ?)
if (pattern.includes('*') || pattern.includes('?')) {
return matchPattern(hostname, pattern, false) || matchPattern(fullUrl, pattern, false);
}
// Smart domene-matching: "facebook.com" matcher også "*.facebook.com"
if (hostname === pattern || hostname.endsWith('.' + pattern)) {
return true;
}
return false;
});
};
if (whitelist.length > 0 && !matchesAnyPattern(whitelist, hostname, url)) {
return true; // whitelist aktiv, men ingen treff
}
if (blacklist.length > 0 && matchesAnyPattern(blacklist, hostname, url)) {
return true;
}
return false;
}
/**
* Sjekk om et felt er i blacklist (basert på ID)
*/
function isFieldBlocked(field) {
if (!field.id || fieldBlacklist.length === 0) return false;
return fieldBlacklist.some(pattern => {
// Support explicit regex with prefix "regex:"
if (pattern.startsWith('regex:')) {
const regexStr = pattern.substring(6); // Remove "regex:"
try {
const regex = new RegExp(regexStr);
return regex.test(field.id);
} catch (e) {
console.error('Invalid blacklist regex:', regexStr, e);
return false;
}
}
// Default to wildcard match
return matchPattern(field.id, pattern, false);
});
}
/**
* Håndter museklikk for å spore siste klikket element
*/
function handleMouseDown(event) {
if (isEditableElement(event.target)) {
lastClickedElement = event.target;
}
}
/**
* Sjekk om et element er redigerbart eller fillbart
*/
function isEditableElement(element) {
if (!element) return false;
const tagName = element.tagName.toLowerCase();
const type = element.type ? element.type.toLowerCase() : '';
// Input-felt (inkludert checkbox, radio, date, etc.)
if (tagName === 'input') {
const fillableTypes = [
'text', 'email', 'password', 'search', 'tel', 'url', 'number',
'checkbox', 'radio',
'date', 'datetime-local', 'time', 'week', 'month',
'color', 'range'
];
return fillableTypes.includes(type);
}
// Select-felt (dropdown)
if (tagName === 'select') {
return true;
}
// Textarea
if (tagName === 'textarea') {
return true;
}
// ContentEditable
if (element.isContentEditable) {
return true;
}
return false;
}
/**
* Hent effektiv URL/hostname (håndterer about:blank/srcdoc ved å sjekke parent)
* Traverserer oppover i iframe-hierarkiet til vi finner en gyldig URL
* Maks 10 nivåer for å unngå uendelig løkke
*/
function getEffectiveLocation() {
let href = window.location.href;
let hostname = window.location.hostname;
let currentWindow = window;
let depth = 0;
const maxDepth = 10;
// Traverser oppover til vi finner en gyldig URL
while ((href === 'about:blank' || href === 'about:srcdoc' || !hostname) && depth < maxDepth) {
try {
if (currentWindow.parent && currentWindow.parent !== currentWindow) {
currentWindow = currentWindow.parent;
// Prøv å lese location - dette kan kaste SecurityError ved cross-origin
href = currentWindow.location.href;
hostname = currentWindow.location.hostname;
depth++;
} else {
// Nådd toppen av hierarkiet
break;
}
} catch (e) {
// Cross-origin blokkering - prøv å bruke document.referrer som fallback
if (document.referrer) {
try {
const referrerUrl = new URL(document.referrer);
href = document.referrer;
hostname = referrerUrl.hostname;
debugLog('Using document.referrer as fallback:', href);
} catch (urlError) {
// Ugyldig referrer URL
debugLog('Could not parse referrer:', document.referrer);
}
}
break;
}
}
// Siste fallback - bruk top.location via postMessage eller aksepter tom
if (!hostname) {
debugLog('Warning: Could not determine effective hostname, using empty');
hostname = '';
}
return { href, hostname, iframeDepth: depth };
}
/**
* Hent regler for gjeldende side
*/
async function loadRulesForCurrentSite(profileId = null) {
try {
const loc = getEffectiveLocation();
// Ikke scan hvis siden er blokkert
if (isBlockedSite(loc.hostname, loc.href)) {
debugLog('Site blokkert - hopper over regel-skann');
const existing = document.getElementById('autofill-scan-toast');
if (existing) existing.remove();
return;
}
// Vis scan-toast: Stadium 1 - Scanning
if (scanToastEnabled) {
showScanToast('scanning');
}
const response = await chrome.runtime.sendMessage({
action: 'getRulesForSite',
url: loc.href,
profileId: profileId
});
if (response && response.success) {
autoFillRules = response.rules;
console.log(`Loaded ${autoFillRules.length} rules for this page (Profile: ${profileId || 'auto'})`);
// Vis scan-toast: Stadium 2 og 3
if (scanToastEnabled) {
if (autoFillRules.length > 0) {
showScanToast('rules-found', autoFillRules.length);
// Vent litt, deretter tell matches
setTimeout(() => {
const fields = findAllEditableFields();
let fullMatches = 0;
let partialMatches = 0;
for (const field of fields) {
const identifier = getFieldIdentifier(field);
if (findMatchingRule(field, identifier)) {
fullMatches++;
}
}
partialMatches = autoFillRules.length - fullMatches;
// Vis scan-toast: Stadium 3 - Match details
showScanToast('match-details', autoFillRules.length, fullMatches, partialMatches);
// Be background oppdatere badge med ferske tall
chrome.runtime.sendMessage({ action: 'refreshBadge' }).catch(() => {});
}, 500);
} else {
// Ingen regler funnet - skjul toast umiddelbart
const existing = document.getElementById('autofill-scan-toast');
if (existing) existing.remove();
}
}
}
} catch (error) {
console.error('Error loading rules:', error);
// Skjul scan-toast ved feil
if (scanToastEnabled) {
const existing = document.getElementById('autofill-scan-toast');
if (existing) existing.remove();
}
}
}
/**
* Utfør automatisk utfylling
*/
function performAutoFill(force = false) {
if (!autofillEnabled && !force) {
debugLog('AutoFill er deaktivert, hopper over');
return;
}
const loc = getEffectiveLocation();
if (isBlockedSite(loc.hostname, loc.href)) {
debugLog('Site blokkert - hopper over autofill');
return;
}
if (autoFillRules.length === 0) {
debugLog('Ingen regler for denne siden');
return;
}
debugLog(`Starter autofill med ${autoFillRules.length} regler`);
// 1. Sjekk for makroer først
for (const rule of autoFillRules) {
if (rule.fieldType === 'macro') {
if (!force && executedMacros.has(rule.id)) {
continue;
}
if (matchesCondition(rule, window.location.href, document.body)) {
// Sjekk om makroens start-element er synlig
let steps;
try {
steps = typeof rule.value === 'string' ? JSON.parse(rule.value) : rule.value;
} catch(e) { continue; }
if (steps && steps.length > 0) {
const firstSelector = steps[0].selector;
const el = document.querySelector(firstSelector);
// Er elementet synlig? (offsetParent er null hvis hidden)
if (el && el.offsetParent !== null) {
console.log('[AutoFill] Macro start element found & visible, running:', firstSelector);
executedMacros.add(rule.id);
const delay = parseInt(rule.delay) || 0;
if (delay > 0) {
console.log(`[AutoFill] Waiting ${delay}ms before executing macro...`);
setTimeout(() => {
MacroPlayer.play(steps);
markRuleAsUsed(rule.id);
}, delay);
} else {
MacroPlayer.play(steps);
markRuleAsUsed(rule.id);
}
} else {
// Debug log kun hvis vi er i debug mode for å unngå spam
debugLog('[AutoFill] Macro start element not visible yet:', firstSelector);
}
}
}
}
}
let filledCount = 0;
const filledFields = [];
const fields = findAllEditableFields();
debugLog(`Funnet ${fields.length} redigerbare felt`);
for (const field of fields) {
if (isFieldBlocked(field)) {
debugLog(`Felt blokkert av field-blacklist: id="${field.id}"`);
continue;
}
const identifier = getFieldIdentifier(field);
if (!identifier) {
debugLog('Felt uten identifikator, sjekker selector-regler', field);
} else {
debugLog(`Sjekker felt: ${identifier.type}="${identifier.value}" (${identifier.fieldType})`);
}
// Finn matchende regel
const matchingRule = findMatchingRule(field, identifier);
if (matchingRule) {
debugLog(`Matchet regel:`, matchingRule);
// Sjekk om feltet allerede har en verdi
const currentValue = getFieldValue(field);
const fieldElementType = identifier?.fieldType || getElementType(field);
if (!force && currentValue && fieldElementType !== 'checkbox' && fieldElementType !== 'radio') {
debugLog(`Felt har allerede verdi: "${currentValue}", hopper over`);
continue;
}
// ENDRING: Prosesser verdi (variabler)
const valueToFill = processValue(matchingRule.value);
fillField(field, valueToFill);
filledCount++;
// Visuell feedback hvis debug mode
if (debugMode) {
highlightField(field);
}
filledFields.push({
identifier: identifier ? identifier.value : matchingRule.fieldPattern,
type: identifier ? identifier.fieldType : matchingRule.elementType || 'text',
value: valueToFill
});
// Marker regelen som brukt
markRuleAsUsed(matchingRule.id);
} else {
if (identifier) {
debugLog(`Ingen matchende regel for: ${identifier.type}="${identifier.value}"`);
} else {
debugLog('Ingen matchende selector-regel for feltet');
}
}
}
if (filledCount > 0) {
debugLog(`AutoFill fullført: Fylte ut ${filledCount} felt`, filledFields);
// Vis notification hvis debug mode eller hvis varsling er aktivert
// ENDRING: Viser notification hvis notificationsEnabled er true
if (notificationsEnabled || debugMode) {
showDebugNotification(`AutoFill: ${filledCount} felt fylt ut`);
}
} else {
debugLog('Ingen felt ble fylt ut');
}
}
// ENDRING: Prosesser variabler i verdi
function processValue(value) {
if (!value || typeof value !== 'string') return value;
const now = new Date();
// Brukerdefinerte variabler
value = value.replace(/{([a-zA-Z0-9_]+)}/g, (match, key) => {
if (userVariables && userVariables[key] !== undefined) {
return userVariables[key];
}
return match;
});
// {date} -> YYYY-MM-DD
if (value.includes('{date}')) {
value = value.replace(/{date}/g, now.toISOString().split('T')[0]);
}
// {time} -> HH:MM:SS
if (value.includes('{time}')) {
value = value.replace(/{time}/g, now.toTimeString().split(' ')[0]);
}
// {timestamp} -> Epoch
if (value.includes('{timestamp}')) {
value = value.replace(/{timestamp}/g, Date.now());
}
// {random} -> tilfeldig tall 0-9999
if (value.includes('{random}')) {
value = value.replace(/{random}/g, Math.floor(Math.random() * 10000));
}
// {random:N} -> tilfeldig tall med N siffer
value = value.replace(/{random:(\d+)}/g, (match, digits) => {
const n = parseInt(digits);
if (isNaN(n)) return match;
const min = Math.pow(10, n - 1);
const max = Math.pow(10, n) - 1;
return Math.floor(min + Math.random() * (max - min + 1));
});
return value;
}
/**
* Trigger autofill med eventuell delay
*/
function triggerAutoFill() {
if (autofillDelayMs > 0) {
setTimeout(performAutoFill, autofillDelayMs);
} else {
performAutoFill();
}
}
/**
* Kjor autofill ved brukerinteraksjon
*/
function attachInteractionTrigger() {
const runOnce = () => {
triggerAutoFill();
document.removeEventListener('focusin', onFocus, true);
document.removeEventListener('click', onClick, true);
};
const onFocus = () => runOnce();
const onClick = () => runOnce();
document.addEventListener('focusin', onFocus, true);
document.addEventListener('click', onClick, true);
}
/**
* Highlight et felt visuelt (kun i debug mode)
*/
function highlightField(field) {
const originalBorder = field.style.border;
const originalBackground = field.style.backgroundColor;
field.style.border = '2px solid #667eea';
field.style.backgroundColor = '#f0f4ff';
field.style.transition = 'all 0.3s ease';
setTimeout(() => {
field.style.border = originalBorder;
field.style.backgroundColor = originalBackground;
}, 2000);
}
/**
* Vis debug notification på siden
*/
function showDebugNotification(message) {
// Translate message if it is the specific autofill message
if (message.startsWith('AutoFill:')) {
const match = message.match(/\d+/);
if (match) {
const count = match[0];
if (currentLanguage === 'no') {
message = `AutoFill: ${count} felt fylt ut`;
} else {
message = `AutoFill: ${count} fields filled`;
}
}
}
// Fjern eksisterende varsel hvis det finnes
const existing = document.getElementById('autofill-notification');
if (existing) existing.remove();
const notification = document.createElement('div');
if (!notification.style) return; // Safety check for XML pages
notification.id = 'autofill-notification';
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 12px 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
z-index: 2147483647; /* Max z-index */
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 14px;
font-weight: 500;
animation: slideIn 0.3s ease-out;
pointer-events: none;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.3s ease';
setTimeout(() => {
if (notification.parentNode) notification.remove();
}, 300);
}, 3000);
}
/**
* Vis scan-toast i øverste venstre hjørne
* @param {string} stage - 'scanning', 'rules-found', eller 'match-details'
* @param {number} rulesCount - Antall regler funnet
* @param {number} fullMatches - Antall full matches
* @param {number} partialMatches - Antall partial matches
*/
function showScanToast(stage, rulesCount = 0, fullMatches = 0, partialMatches = 0) {
if (!scanToastEnabled) return;
// Fjern eksisterende toast
const existing = document.getElementById('autofill-scan-toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.id = 'autofill-scan-toast';
// Safety check for non-HTML pages (XML/SVG)
if (!toast.style) return;
let content = '';
let autoHide = false;
let hideDelay = 0;
if (stage === 'scanning') {
content = currentLanguage === 'no' ? 'Skanner...' : 'Scanning...';
} else if (stage === 'rules-found') {
const rulesText = currentLanguage === 'no' ?
`${rulesCount} ${rulesCount === 1 ? 'regel' : 'regler'} funnet for denne siden` :
`${rulesCount} ${rulesCount === 1 ? 'rule' : 'rules'} found for this page`;
content = rulesText;
} else if (stage === 'match-details') {
const rulesText = currentLanguage === 'no' ?
`${rulesCount} ${rulesCount === 1 ? 'regel' : 'regler'} funnet for denne siden` :
`${rulesCount} ${rulesCount === 1 ? 'rule' : 'rules'} found for this page`;
const matchesText = currentLanguage === 'no' ?
`${fullMatches} ${fullMatches === 1 ? 'match' : 'matches'}` :
`${fullMatches} ${fullMatches === 1 ? 'match' : 'matches'}`;
const partialText = currentLanguage === 'no' ?
`${partialMatches} partial ${partialMatches === 1 ? 'match' : 'matches'}` :