-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
898 lines (779 loc) · 34.9 KB
/
content.js
File metadata and controls
898 lines (779 loc) · 34.9 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
/**
* HEYBRO CONTENT SCRIPT - ROCK SOLID ARCHITECTURE
*
* Modules:
* 1. State & Logging
* 2. VisualCheck: Visibility & Overlay detection
* 3. SmartLocator: Dynamic element discovery
* 4. InteractionEngine: Framework-compatible events
* 5. Execution: Main dispatcher
*/
// --- 1. State & Logging ---
var state = window.__heybro_state || {};
state.nextId = state.nextId || 1;
state.map = state.map || new Map();
state.sigMap = state.sigMap || new Map();
state.sigIndex = state.sigIndex || new Map();
state.badges = state.badges || [];
state.badgeMap = state.badgeMap || new Map();
state.annotating = state.annotating !== undefined ? state.annotating : false;
state.experimental = state.experimental !== undefined ? state.experimental : false;
window.__heybro_state = state;
if (!window.__heybro_logger_init) {
window.__heybro_logger_init = true;
const log = (t, d) => { try { chrome.runtime.sendMessage({ t: "EVENT_LOG", event: t, detail: d, url: location.href }); } catch { } };
// Passive event listeners for activity tracking
['click', 'input', 'change', 'scroll'].forEach(evt => {
document.addEventListener(evt, (e) => {
if (!e.isTrusted) return; // Ignore synthetic events for logging
if (evt === 'scroll') { log('scroll', { y: window.scrollY }); return; }
const el = e.target;
log(evt, {
tag: el.tagName?.toLowerCase(),
id: el.id,
text: (el.innerText || el.value || "").slice(0, 50)
});
}, { capture: true, passive: true });
});
// Active interaction tracking for verification
window.__hb_last_interaction = null;
['click', 'input', 'change', 'scroll'].forEach(evt => {
document.addEventListener(evt, (e) => {
if (!e.isTrusted) return;
const el = e.target;
window.__hb_last_interaction = {
type: evt,
ts: Date.now(),
target: {
tag: el.tagName?.toLowerCase(),
id: el.id,
text: (el.innerText || el.value || "").slice(0, 50),
path: getDomPath(el)
}
};
}, { capture: true, passive: true });
});
function getDomPath(el) {
if (!el) return '';
const stack = [];
while (el.parentNode != null) {
let sibCount = 0;
let sibIndex = 0;
for (let i = 0; i < el.parentNode.childNodes.length; i++) {
const sib = el.parentNode.childNodes[i];
if (sib.nodeName == el.nodeName) {
if (sib === el) sibIndex = sibCount;
sibCount++;
}
}
if (el.hasAttribute('id') && el.id != '') {
stack.unshift(el.nodeName.toLowerCase() + '#' + el.id);
} else if (sibCount > 1) {
stack.unshift(el.nodeName.toLowerCase() + ':eq(' + sibIndex + ')');
} else {
stack.unshift(el.nodeName.toLowerCase());
}
el = el.parentNode;
}
return stack.slice(1).join(' > '); // slice(1) to remove document
}
// Mutation Observer for State Detection
window.__hb_mutation_count = 0;
window.__hb_last_mutation_ts = Date.now();
if (!window.__hb_observer) {
window.__hb_observer = new MutationObserver((mutations) => {
window.__hb_mutation_count += mutations.length;
window.__hb_last_mutation_ts = Date.now();
});
window.__hb_observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
characterData: true,
attributeFilter: ['class', 'style', 'disabled', 'value', 'aria-label', 'role'] // Filter to relevant attributes
});
}
}
// --- 2. VisualCheck ---
window.VisualCheck = {
isVisible: function (el) {
if (!el) return false;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') return false;
// Special handling for Google Sheets and accessibility elements
// They might be transparent (opacity 0) but are still interactive via the grid
const role = el.getAttribute('role');
if (role === 'gridcell' || role === 'textbox' || role === 'button') {
return true;
}
if (style.opacity === '0') return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
},
isObscured: function (el) {
if (!el) return true;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return true;
// Check center point
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
const topEl = document.elementFromPoint(x, y);
if (!topEl) return true;
if (topEl === el || el.contains(topEl) || topEl.contains(el)) return false;
// Check corners if center is obscured
const points = [
{ x: rect.left + 1, y: rect.top + 1 },
{ x: rect.right - 1, y: rect.top + 1 },
{ x: rect.left + 1, y: rect.bottom - 1 },
{ x: rect.right - 1, y: rect.bottom - 1 }
];
for (const p of points) {
const pointEl = document.elementFromPoint(p.x, p.y);
if (pointEl && (pointEl === el || el.contains(pointEl) || pointEl.contains(el))) return false;
}
return true;
}
};
// --- 3. SmartLocator ---
window.SmartLocator = {
clean(str) {
return String(str || "").toLowerCase().replace(/\s+/g, " ").trim();
},
score(el, criteria) {
if (!window.VisualCheck.isVisible(el)) return -1;
let score = 0;
const text = this.clean(el.innerText || el.textContent);
const value = this.clean(el.value);
const label = this.clean(el.getAttribute('aria-label') || el.getAttribute('name') || "");
const placeholder = this.clean(el.getAttribute('placeholder'));
const id = this.clean(el.id);
const testId = this.clean(el.getAttribute('data-testid') || el.getAttribute('data-test') || el.getAttribute('data-qa'));
const href = this.clean(el.href || el.getAttribute('href'));
const role = this.clean(el.getAttribute('role'));
const tag = el.tagName.toLowerCase();
const className = this.clean(el.className);
// 1. Exact ID/TestID match (High confidence)
if (criteria.id && (id === criteria.id || testId === criteria.id)) score += 100;
// 2. Text/Label Match
if (criteria.text) {
const target = this.clean(criteria.text);
if (text === target || value === target) score += 50;
else if (text.includes(target) || value.includes(target)) score += 20;
if (label === target) score += 40;
else if (label.includes(target)) score += 15;
if (placeholder === target) score += 30;
}
// 3. Attributes
if (criteria.href && href.includes(this.clean(criteria.href))) score += 30;
if (criteria.role && role === criteria.role) score += 10;
if (criteria.tag && tag === criteria.tag) score += 5;
// 4. Class Name Heuristics (e.g. "btn", "button")
if (className.includes("btn") || className.includes("button")) score += 5;
// 5. Viewport Bonus
// Removed VisualCheck.isInViewport, so this bonus is removed or needs re-evaluation
// if (VisualCheck.isInViewport(el)) score += 5;
return score;
},
find(payload) {
// Strategy 1: Internal Map ID Lookup (Fastest & Most Reliable)
if (payload.id) {
// Check internal map first - this is the ID we assigned
const mapped = state.map.get(parseInt(payload.id));
if (mapped && window.VisualCheck.isVisible(mapped)) {
// Zero Point Failure: Validate content if signature is present
// This prevents clicking the wrong element if IDs are reused or shifted
if (payload.sig && payload.sig.text) {
const t1 = this.clean(payload.sig.text);
const t2 = this.clean(mapped.innerText || mapped.value || mapped.textContent);
// Only reject if both have text and they are significantly different
if (t1 && t2 && t1 !== t2 && !t2.includes(t1) && !t1.includes(t2)) {
// console.warn("SmartLocator: ID match rejected due to text mismatch", { id: payload.id, expected: t1, actual: t2 });
// Fall through to other strategies
} else {
return mapped;
}
} else {
return mapped;
}
}
}
// Strategy 2: Direct Selector
if (payload.selector) {
try {
const el = document.querySelector(payload.selector);
if (el && window.VisualCheck.isVisible(el)) return el;
} catch { }
}
// Strategy 3: DOM ID Lookup
if (payload.id) {
const el = document.getElementById(payload.id);
if (el && window.VisualCheck.isVisible(el)) return el;
}
// Strategy 4: Scoring Scan (Robust Fallback)
// Expanded candidates to include potential interactive divs/spans
const candidates = document.querySelectorAll('a, button, input, textarea, select, [role], [onclick], [tabindex], div[class*="btn"], span[class*="btn"], div[class*="button"], span[class*="button"]');
let bestEl = null;
let bestScore = 0;
// Normalize payload for scoring
const criteria = {
id: payload.id ? this.clean(payload.id) : null,
text: payload.text ? this.clean(payload.text) : null,
href: payload.href ? this.clean(payload.href) : null,
role: payload.role ? this.clean(payload.role) : null,
tag: payload.tag ? this.clean(payload.tag) : null
};
// If we have a signature from a previous map, merge it
if (payload.element) {
if (!criteria.text && payload.element.x) criteria.text = this.clean(payload.element.x);
if (!criteria.tag && payload.element.t) criteria.tag = this.clean(payload.element.t);
if (!criteria.role && payload.element.r) criteria.role = this.clean(payload.element.r);
if (!criteria.href && payload.element.h) criteria.href = this.clean(payload.element.h);
} else if (payload.sig) {
if (!criteria.text) criteria.text = this.clean(payload.sig.text);
if (!criteria.tag) criteria.tag = this.clean(payload.sig.tag);
if (!criteria.role) criteria.role = this.clean(payload.sig.role);
}
for (const el of candidates) {
const s = this.score(el, criteria);
if (s > bestScore) {
bestScore = s;
bestEl = el;
}
}
// Lower threshold slightly to be more forgiving
if (bestScore > 5) return bestEl;
// Strategy 5: XPath Fallback
if (payload.xpath) {
try {
const res = document.evaluate(payload.xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (res.singleNodeValue && VisualCheck.isVisible(res.singleNodeValue)) return res.singleNodeValue;
} catch { }
}
// Log failure for debugging
if (payload.id || payload.text || payload.selector) {
// console.warn("SmartLocator failed to find element:", payload, "Best Score:", bestScore);
}
return null;
}
};
// --- 4. InteractionEngine ---
window.InteractionEngine = {
async scrollIntoView(el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
await new Promise(r => setTimeout(r, 500)); // Wait for scroll
},
async click(el, force = false) {
await this.scrollIntoView(el);
if (!force && VisualCheck.isObscured(el)) {
// console.warn("Element appears obscured, forcing native click");
force = true;
}
// Analyze the element to predict behavior
const linkInfo = this.analyzeLinkBehavior(el);
// Store link info for the tap function to use
if (linkInfo.willOpenNewTab) {
window.__hb_expecting_new_tab = {
href: linkInfo.href,
timestamp: Date.now(),
elementInfo: {
tag: el.tagName,
id: el.id,
text: (el.textContent || '').slice(0, 50)
}
};
// Clear after 3 seconds
setTimeout(() => {
delete window.__hb_expecting_new_tab;
}, 3000);
}
const rect = el.getBoundingClientRect();
const opts = {
bubbles: true, cancelable: true, view: window,
clientX: rect.left + rect.width / 2,
clientY: rect.top + rect.height / 2,
buttons: 1
};
// Full event sequence for modern frameworks
el.dispatchEvent(new PointerEvent('pointerover', opts));
el.dispatchEvent(new MouseEvent('mouseover', opts));
el.dispatchEvent(new PointerEvent('pointerenter', opts));
el.dispatchEvent(new MouseEvent('mouseenter', opts));
el.dispatchEvent(new PointerEvent('pointerdown', opts));
el.dispatchEvent(new MouseEvent('mousedown', opts));
el.focus();
el.dispatchEvent(new PointerEvent('pointerup', opts));
el.dispatchEvent(new MouseEvent('mouseup', opts));
el.dispatchEvent(new MouseEvent('click', opts));
// Final fallback for super stubborn elements
if (force) {
try { el.click(); } catch { }
}
return true;
},
analyzeLinkBehavior(el) {
// Analyze element to predict if it will open a new tab
const info = {
href: null,
willOpenNewTab: false,
hasTarget: false,
targetValue: null,
hasOnClick: false
};
// Check if it's a link or has a click handler
const isLink = el.tagName?.toLowerCase() === 'a';
const href = el.href || el.getAttribute('href');
const target = el.target || el.getAttribute('target');
const hasOnClick = el.onclick || el.getAttribute('onclick');
info.href = href;
info.hasTarget = !!target;
info.targetValue = target;
info.hasOnClick = !!hasOnClick;
// Predict new tab opening
if (isLink && target && (target === '_blank' || target === '_new')) {
info.willOpenNewTab = true;
}
// Check parent elements for target
let parent = el.parentElement;
while (parent && !info.willOpenNewTab) {
const parentTarget = parent.target || parent.getAttribute('target');
if (parent.tagName?.toLowerCase() === 'a' && parentTarget && (parentTarget === '_blank' || parentTarget === '_new')) {
info.willOpenNewTab = true;
if (!info.href) {
info.href = parent.href || parent.getAttribute('href');
}
}
parent = parent.parentElement;
}
return info;
},
async type(el, value, append = false) {
await this.scrollIntoView(el);
el.focus();
const isContentEditable = el.isContentEditable || el.contentEditable === 'true';
if (isContentEditable) {
// Handle contenteditable divs (like Gmail compose, Twitter/X)
// Strategy: Use Selection API to select all (if replacing) or collapse to end (if appending)
// then use execCommand 'insertText' which mimics native user typing and triggers correct events.
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
selection.removeAllRanges();
selection.addRange(range);
if (append) {
selection.collapseToEnd();
}
// 'insertText' will replace the selection (which is everything if !append)
// This is much more robust than setting textContent = '' which breaks some editors (Draft.js, etc)
document.execCommand('insertText', false, value);
// Dispatch events for frameworks
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
// Dispatch events for frameworks
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
return {
typed: true,
actual: el.innerText || el.textContent || '',
attempted: value,
append: append
};
} else {
// Handle standard input/textarea elements
const tagName = el.tagName?.toLowerCase();
let setter;
try {
if (tagName === 'textarea') {
setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set;
} else if (tagName === 'input') {
setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
}
} catch (e) {
// Descriptor access failed, fall back to direct assignment
setter = null;
}
const newValue = append ? (el.value || '') + value : value;
if (setter) {
setter.call(el, newValue);
} else {
el.value = newValue;
}
// Dispatch events
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
// Simulate keypresses
el.dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true }));
el.dispatchEvent(new KeyboardEvent('keyup', { key: 'End', bubbles: true }));
// Verify the result
let actualValue = '';
if (isContentEditable) {
actualValue = el.innerText || el.textContent || '';
} else {
actualValue = el.value || '';
}
// Calculate what we expected
// Note: This is an approximation. If 'append' is true, we expect (original + value).
// But we didn't capture original perfectly before.
// For now, we just return what is THERE, and let the agent decide if it matches what it wanted.
return {
typed: true,
actual: actualValue,
attempted: value,
append: append
};
}
}
};
// --- 5. Execution ---
async function execute(payload) {
const action = payload.action;
// Global Actions
if (action === 'new_tab') {
if (payload.url) try { chrome.runtime.sendMessage({ action: "OPEN_NEW_TAB", url: payload.url }); } catch { }
return { ok: true };
}
if (action === 'scroll') {
if (payload.to === 'top') window.scrollTo({ top: 0, behavior: 'smooth' });
else if (payload.to === 'bottom') window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
else if (payload.amount) window.scrollBy({ top: payload.amount, behavior: 'smooth' });
else {
// Scroll to element
const target = SmartLocator.find(payload);
if (target) await InteractionEngine.scrollIntoView(target);
else window.scrollBy({ top: window.innerHeight * 0.8, behavior: 'smooth' });
}
await new Promise(r => setTimeout(r, 300));
return { ok: true };
}
// Element Actions
const el = SmartLocator.find(payload);
if (!el) {
return { ok: false, error: "Element not found" };
}
if (action === 'click' || action === 'tap') {
await InteractionEngine.click(el, payload.force);
return { ok: true, clicked: true };
}
if (action === 'type') {
const result = await InteractionEngine.type(el, payload.value || payload.text, payload.append);
if (payload.submit) {
el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', which: 13, keyCode: 13, bubbles: true }));
el.dispatchEvent(new KeyboardEvent('keypress', { key: 'Enter', code: 'Enter', which: 13, keyCode: 13, bubbles: true }));
el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', which: 13, keyCode: 13, bubbles: true }));
}
return { ok: true, ...result };
}
if (action === 'press') {
const key = payload.key;
const modifiers = payload.modifiers || [];
if (!key) {
return { ok: false, error: "No key specified" };
}
try {
const mods = {
ctrlKey: modifiers.some(m => String(m).toLowerCase().includes("ctrl")),
shiftKey: modifiers.some(m => String(m).toLowerCase().includes("shift")),
altKey: modifiers.some(m => String(m).toLowerCase().includes("alt")),
metaKey: modifiers.some(m => String(m).toLowerCase().includes("meta"))
};
const code = key === "Enter" ? "Enter" : key;
const keyEventInit = { key, code, bubbles: true, cancelable: true, ...mods, view: window };
// Helper to dispatch with legacy properties
const dispatchKey = (type) => {
const e = new KeyboardEvent(type, keyEventInit);
// Try to define legacy properties if possible
try { Object.defineProperty(e, 'keyCode', { get: () => key === "Enter" ? 13 : 0 }); } catch { }
try { Object.defineProperty(e, 'which', { get: () => key === "Enter" ? 13 : 0 }); } catch { }
el.dispatchEvent(e);
};
dispatchKey("keydown");
dispatchKey("keypress");
dispatchKey("keyup");
let submitted = false;
if (String(key).toLowerCase() === "enter") {
const form = (el && (el.form || (el.closest && el.closest("form")))) || document.querySelector("form");
if (form) {
if (typeof form.requestSubmit === "function") {
form.requestSubmit();
} else {
const btn = form.querySelector("button[type='submit'], input[type='submit']");
if (btn) {
btn.click();
} else {
form.submit();
}
}
submitted = true;
} else {
const btn = document.querySelector("button[type='submit'], input[type='submit']");
if (btn) {
btn.click();
submitted = true;
}
}
}
try { window.__hb_last_key = key; } catch { }
return { ok: true, key, modifiers, submitted };
} catch (error) {
return { ok: false, error: error.message };
}
}
if (action === 'focus') {
el.focus();
return { ok: true, focused: true };
}
return { ok: false, error: `Unknown action: ${action}` };
}
// --- 6. PageScanner ---
window.PageScanner = {
walk(root, out) {
const stack = [root];
const seen = new Set();
while (stack.length) {
const node = stack.pop();
if (!node || seen.has(node)) continue;
seen.add(node);
if (node.nodeType === 1) {
const el = node;
const tag = el.tagName.toLowerCase();
if (VisualCheck.isVisible(el)) {
// Check if interactive
const role = el.getAttribute('role');
const hasClick = el.hasAttribute('onclick') || el.getAttribute('tabindex') === '0';
const hasHref = el.hasAttribute('href'); // Links with href are always interactive
const isInput = ['a', 'button', 'input', 'textarea', 'select', 'details', 'summary'].includes(tag);
const isRole = ['button', 'link', 'menuitem', 'tab', 'checkbox', 'radio', 'switch', 'combobox', 'textbox', 'gridcell', 'option', 'treeitem'].includes(role);
// Refined cursor check: only if leaf node or has specific attributes
const style = getComputedStyle(el);
const isPointer = style.cursor === 'pointer';
const isLeaf = el.children.length === 0 && String(el.innerText || "").trim().length > 0;
// Exclude generic containers unless they have explicit interactive traits
const isGeneric = tag === 'div' || tag === 'span' || tag === 'section' || tag === 'body' || tag === 'html';
const isInteractive =
isInput ||
isRole ||
hasClick ||
hasHref || // Any element with href should be tagged
tag === 'canvas' || // Explicitly include canvas
(isPointer && (isLeaf || !isGeneric));
if (isInteractive) out.push(el);
}
const sr = el.shadowRoot;
if (sr) stack.push(sr);
if (tag === 'iframe') {
try {
const doc = el.contentDocument || el.contentWindow?.document;
if (doc && doc.documentElement) stack.push(doc.documentElement);
} catch { }
}
}
const children = node.children || node.childNodes;
if (children) {
for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);
}
}
},
simplify(annotate) {
state.map.clear();
state.badges.forEach(b => b.remove());
state.badges = [];
// state.nextId = 1; // Removed to ensure unique IDs across turns
const els = [];
this.walk(document, els);
// Deduplication Logic
const groups = [];
const THRESHOLD = 5; // pixels
for (const el of els) {
const r = el.getBoundingClientRect();
let added = false;
for (const group of groups) {
const gr = group.rect;
if (Math.abs(r.left - gr.left) < THRESHOLD &&
Math.abs(r.top - gr.top) < THRESHOLD &&
Math.abs(r.width - gr.width) < THRESHOLD &&
Math.abs(r.height - gr.height) < THRESHOLD) {
group.candidates.push(el);
added = true;
break;
}
}
if (!added) {
groups.push({ rect: r, candidates: [el] });
}
}
const finalEls = [];
for (const group of groups) {
// Select best candidate from group
// Preference: button > a > input > textarea > select > [role=button] > leaf node > others
group.candidates.sort((a, b) => {
const score = (el) => {
let s = 0;
const tag = el.tagName.toLowerCase();
if (tag === 'button') s += 10;
else if (tag === 'a') s += 9;
else if (tag === 'input') s += 8;
else if (tag === 'textarea') s += 8;
else if (tag === 'select') s += 8;
else if (el.getAttribute('role') === 'button') s += 7;
else if (el.getAttribute('role') === 'link') s += 6;
else if (el.getAttribute('role') === 'gridcell') s += 15; // High priority for gridcells
else if (el.getAttribute('role') === 'textbox') s += 14; // High priority for textboxes
if (!el.children.length) s += 2; // Leaf node preference
if (String(el.innerText || "").trim().length > 0) s += 1;
return s;
};
return score(b) - score(a);
});
finalEls.push(group.candidates[0]);
}
const nodes = [];
for (const el of finalEls) {
const id = state.nextId++;
state.map.set(id, el);
el.dataset.agentId = String(id);
const r = el.getBoundingClientRect();
if (annotate) {
const b = document.createElement('div');
b.textContent = id;
b.style.cssText = `position:fixed;z-index:2147483647;background:#000;color:#fff;font-size:10px;padding:1px 3px;border-radius:3px;pointer-events:none;opacity:0.8;`;
b.style.left = Math.max(0, r.left) + 'px';
b.style.top = Math.max(0, r.top) + 'px';
document.body.appendChild(b);
state.badges.push(b);
}
nodes.push({
i: id,
t: el.tagName.toLowerCase(),
x: String(el.innerText || el.value || "").slice(0, 50).replace(/\s+/g, " ").trim(),
l: (el.getAttribute('aria-label') || el.getAttribute('name') || "").slice(0, 50),
r: el.getAttribute('role') || "",
b: { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) }
});
}
return nodes;
},
mapCompact() {
// Similar to simplify but returns compact format for experimental mode
state.map.clear();
// state.nextId = 1; // Removed to ensure unique IDs across turns
const els = [];
this.walk(document, els);
return els.map(el => {
const id = state.nextId++;
state.map.set(id, el);
el.dataset.agentId = String(id);
const r = el.getBoundingClientRect();
return {
i: id,
t: el.tagName.toLowerCase(),
x: String(el.innerText || el.value || "").slice(0, 100).replace(/\s+/g, " ").trim(),
l: (el.getAttribute('aria-label') || "").slice(0, 50),
r: el.getAttribute('role') || undefined,
h: el.getAttribute('href') || undefined,
p: el.getAttribute('placeholder') || undefined,
b: { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) }
};
});
}
};
// --- Listener Setup ---
window.__HEYBRO_CONTENT_VERSION = 1764211243803; // Timestamp for version check
if (!window.__heybro_listener_added) {
window.__heybro_listener_added = true;
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.t === "ping") {
sendResponse({ pong: true, version: window.__HEYBRO_CONTENT_VERSION });
return;
}
if (msg.t === "execute") {
execute(msg.payload).then(res => sendResponse(res)).catch(e => sendResponse({ ok: false, error: e.message }));
return true;
}
if (msg.t === "evaluate") {
try {
const result = eval(msg.code);
sendResponse({ ok: true, result });
} catch (e) {
sendResponse({ ok: false, error: e.message });
}
return;
}
if (msg.t === "simplify") {
// Filter out irrelevant frames (GTM, ads, etc) ONLY if we are in an iframe
if (window !== window.top && /googletagmanager|doubleclick|facebook\.com\/tr|google-analytics|ads\.google/.test(location.href)) {
sendResponse({ elements: [] });
return;
}
try {
const els = window.PageScanner.simplify(msg.annotate);
sendResponse({ elements: els });
} catch (e) {
console.error("Heybro: simplify error", e);
sendResponse({ elements: [], error: e.message });
}
return;
}
if (msg.t === "mapCompact") {
// Filter out irrelevant frames ONLY if we are in an iframe
if (window !== window.top && /googletagmanager|doubleclick|facebook\.com\/tr|google-analytics|ads\.google/.test(location.href)) {
sendResponse({ elements: [] });
return;
}
try {
const els = window.PageScanner.mapCompact();
sendResponse({ elements: els });
} catch (e) {
sendResponse({ elements: [], error: e.message });
}
return;
}
if (msg.t === "getPageState") {
try {
const sel = window.getSelection();
const active = document.activeElement;
let currentUrl = location.href;
let isIframe = window !== window.top;
try {
// Try to get top URL if possible (same origin)
if (isIframe && window.top.location.href) {
currentUrl = window.top.location.href;
isIframe = false; // Treat as top if we can access it
}
} catch { }
sendResponse({
state: {
url: currentUrl,
title: document.title,
readyState: document.readyState,
scroll: { y: window.scrollY, x: window.scrollX },
selectedText: sel ? sel.toString() : "",
activeElement: active ? {
tag: active.tagName.toLowerCase(),
type: active.type || "",
text: (active.innerText || active.value || "").slice(0, 50)
} : null,
lastInteraction: window.__hb_last_interaction,
mutationCount: window.__hb_mutation_count,
isIframe: isIframe
}
});
} catch (e) {
sendResponse({ state: { url: location.href, error: e.message } });
}
return;
}
if (msg.t === "getFormState") {
try {
const forms = {};
document.querySelectorAll('form').forEach((f, i) => {
const data = {};
new FormData(f).forEach((v, k) => data[k] = v);
forms[`form_${i}`] = data;
});
sendResponse({ state: forms });
} catch (e) {
sendResponse({ state: {} });
}
return;
}
});
}