-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontentScript.js
1075 lines (943 loc) · 32.3 KB
/
contentScript.js
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
// contentScript.js
// Keep track of the cursor element
let cursorElement = null;
// Add a global map to store interactive elements by index
let interactiveElementsMap = [];
let doHighlightElements = 0;
// Store the original title to restore it later
let originalTitle = null;
// Function to reset the interactive elements tracking
function resetInteractiveElements() {
interactiveElementsMap = [];
currentHighlightIndex = 0;
}
// Function to get element by index
function getElementByIndex(index) {
console.log("Getting element by index:", index);
const elementData = interactiveElementsMap[index];
console.log("Interactive elements map:", elementData);
return elementData ? getLocateElement(elementData) : null;
// return elementData ? findElementBySelector(elementData.xpath) : null;
}
// ==========================================================
// 1) Utility to build a CSS selector from an element object
// (similar to the earlier snippet):
// ==========================================================
function convertSimpleXPathToCssSelector(xpath) {
if (!xpath) return '';
// Remove leading slashes
const normalized = xpath.replace(/^\/+/, '');
const parts = normalized.split('/');
const cssParts = [];
for (const part of parts) {
if (!part) continue;
if (part.includes('[')) {
// Something like div[1], div[last()]
const bracketIndex = part.indexOf('[');
let basePart = part.slice(0, bracketIndex);
const indexPart = part.slice(bracketIndex);
// e.g. "[1][2]" => split on ']' => ["[1","[2",""]
const indices = indexPart.split(']').filter(Boolean).map(s => s.replace('[', ''));
for (const idx of indices) {
if (/^\d+$/.test(idx)) {
const num = parseInt(idx, 10);
basePart += `:nth-of-type(${num})`;
} else if (idx === 'last()') {
basePart += ':last-of-type';
} else if (idx.includes('position()') && idx.includes('>1')) {
basePart += ':nth-of-type(n+2)';
}
}
cssParts.push(basePart);
} else {
cssParts.push(part);
}
}
return cssParts.join(' > ');
}
// Some set of "safe" attributes you want to include in the selector:
const SAFE_ATTRIBUTES = new Set([
'id',
'name',
'type',
'value',
'placeholder',
'aria-label',
'aria-labelledby',
'aria-describedby',
'role',
'for',
'autocomplete',
'required',
'readonly',
'alt',
'title',
'src',
'data-testid',
'data-id',
'data-qa',
'data-cy',
'href',
'target',
]);
const VALID_CLASS_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;
/**
* Builds a more descriptive CSS selector from:
* - The element's XPath (converted)
* - Classes
* - Additional "safe" attributes
*/
function enhancedCssSelectorForElement(element) {
try {
let cssSelector = convertSimpleXPathToCssSelector(element.xpath);
// If there's a class attribute, append valid class names
if (element.attributes && element.attributes.class) {
const classes = element.attributes.class.split(/\s+/).filter(Boolean);
for (const cls of classes) {
if (VALID_CLASS_NAME_REGEX.test(cls)) {
cssSelector += `.${cls}`;
}
}
}
// Append additional safe attributes
for (const [attr, value] of Object.entries(element.attributes || {})) {
// skip class (already handled)
if (attr === 'class') continue;
if (!attr.trim()) continue; // skip empty attribute name
if (!SAFE_ATTRIBUTES.has(attr)) continue;
// escape colons in attribute name
const safeAttr = attr.replace(':', '\\:');
if (value === '') {
// e.g. [required], [checked], ...
cssSelector += `[${safeAttr}]`;
} else if (/["'<>`]/.test(value)) {
// If special chars, do a "contains" match
const safeValue = value.replace(/"/g, '\\"');
cssSelector += `[${safeAttr}*="${safeValue}"]`;
} else {
cssSelector += `[${safeAttr}="${value}"]`;
}
}
return cssSelector || element.tagName;
} catch (err) {
// fallback
const tagName = element.tagName || '*';
const highlightIndex = element.highlightIndex;
return `${tagName}[highlight_index='${highlightIndex}']`;
}
}
// ==========================================================
// 2) Native "getLocateElement" function to find the element
// directly in the DOM (without Puppeteer/Playwright).
// ==========================================================
/**
* Locates a DOM element in the current page/extension context,
* even if it's inside an iframe. We walk up the element's
* "parent" chain to see if we have an iframe ancestor, then
* query inside that frame's contentDocument.
*
* @param {Object} element - The DOM node object with { parent, tag_name, xpath, attributes, highlightIndex, ... }
* @param {Document} doc - The root Document to start from (usually window.document).
* @returns {HTMLElement|null}
*/
function getLocateElement(elementData, doc = document) {
const elementSelector = enhancedCssSelectorForElement(elementData)
let elHandle = doc.querySelector(elementSelector);
if (elHandle) {
elHandle.scrollIntoView?.({ block: "nearest", inline: "nearest" });
return elHandle;
}
// recursively loop through the parents and if a parent has a shadowRoot, call getLocateElement on it.
// find the first shadowRoot parent and use that for the query.
let shadowRootParent = elementData;
while (shadowRootParent.parent) {
shadowRootParent = shadowRootParent.parent;
if (shadowRootParent.shadowRoot) {
break;
}
}
if (shadowRootParent && shadowRootParent.shadowRoot) {
console.log("Locating shadowRoot parent", shadowRootParent);
const parentNode = getLocateElement(shadowRootParent);
if (!parentNode) {
return null;
}
if (parentNode.shadowRoot) {
console.log("parentNode", parentNode);
console.log("elementSelector", elementSelector);
elHandle = parentNode.shadowRoot.querySelector(elementSelector);
}
if (!elHandle) {
elHandle = parentNode.querySelector(elementSelector);
}
if (!elHandle) {
return null;
} else {
elHandle.scrollIntoView?.({ block: "nearest", inline: "nearest" });
return elHandle;
}
}
let iframeParent = elementData;
while (iframeParent.parent) {
iframeParent = iframeParent.parent;
if (iframeParent.tagName === "iframe") {
break;
}
}
if (iframeParent && iframeParent.tagName === "iframe") {
const parentNode = getLocateElement(iframeParent);
if (!parentNode) {
return null;
}
elHandle = parentNode.contentDocument.querySelector(elementSelector);
if (!elHandle) {
return null;
} else {
elHandle.scrollIntoView?.({ block: "nearest", inline: "nearest" });
return elHandle;
}
}
}
// Function to determine if a selector is XPath or CSS
function isXPath(selector) {
return (
selector.startsWith("/") ||
selector.startsWith("./") ||
selector.startsWith("(")
);
}
function findElementBySelector(selector) {
const result = document.evaluate(
selector,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
);
return result.singleNodeValue;
}
// Initialize cursor in the middle of the viewport when extension is activated
async function initializeCursor() {
// Only initialize cursor in the top frame
if (window.top !== window.self) {
return;
}
// Wait for document to be ready
if (!isDocumentReady()) {
// Retry after a short delay if document is not ready
await new Promise(resolve => setTimeout(resolve, 500));
if (!isDocumentReady()) {
console.warn('Document not ready for cursor initialization');
return;
}
}
// Check if body exists
if (!document.body) {
console.warn('Document body not available for cursor initialization');
return;
}
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const x = viewportWidth / 2;
const y = viewportHeight / 2;
updateCursor(x, y);
}
// Animate cursor movement to target position
async function animateCursorTo(targetX, targetY, duration = 500) {
if (!cursorElement) {
initializeCursor();
}
const startRect = cursorElement.getBoundingClientRect();
const startX = startRect.left;
const startY = startRect.top;
const startTime = performance.now();
return new Promise((resolve) => {
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// Easing function for smooth movement
const easeOutCubic = (progress) => 1 - Math.pow(1 - progress, 3);
const easeProgress = easeOutCubic(progress);
const currentX = startX + (targetX - startX) * easeProgress;
const currentY = startY + (targetY - startY) * easeProgress;
updateCursor(currentX, currentY);
if (progress < 1) {
requestAnimationFrame(animate);
} else {
// Ensure we end exactly at the target position
updateCursor(targetX, targetY);
// Add a small delay after reaching the target
setTimeout(resolve, 100);
}
}
requestAnimationFrame(animate);
});
}
// Update the click handler to use cursor animation
async function handleClick(elementData) {
try {
if (!elementData) {
console.error("No element data provided");
return false;
}
const element = getLocateElement(elementData);
console.log("Clickable element:", element);
if (!element) {
console.warn(`Element not found with selector: ${elementData.xpath}`);
return false;
}
// Get element center coordinates for visual feedback
const rect = element.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
// Highlight the element
const originalOutline = element.style.outline;
element.style.outline = "2px solid red";
try {
// Wait for cursor animation to complete
await animateCursorTo(x, y);
// Show click animation and wait for it
await new Promise(resolve => {
showClickIndicator(x, y);
setTimeout(resolve, 500); // Match the click indicator animation duration
});
// Try native click() if element supports it
if (typeof element.click === 'function') {
try {
element.click();
// Wait for any click-triggered animations or state changes
await new Promise(resolve => setTimeout(resolve, 500));
return true;
} catch (error) {
console.log('Native click() failed:', error);
}
}
// Trigger events after cursor reaches the target only if native click failed
["mousedown", "mouseup", "click"].forEach((eventType) => {
element.dispatchEvent(
new MouseEvent(eventType, {
view: window,
bubbles: true,
cancelable: true,
clientX: x,
clientY: y
})
);
});
// Wait for events to propagate
await new Promise(resolve => setTimeout(resolve, 500));
// Remove highlight after a delay
element.style.outline = originalOutline;
return true;
} catch (error) {
element.style.outline = originalOutline;
throw error;
}
} catch (error) {
console.error("Error in click handler:", error);
return false;
}
}
// Add cleanup function
function cleanupExtensionMarkup() {
try {
// Remove the highlight container and all its contents
const container = document.getElementById("playwright-highlight-container");
if (container) {
container.remove();
}
// Remove highlight attributes from elements
const highlightedElements = document.querySelectorAll(
'[browser-user-highlight-id^="playwright-highlight-"]'
);
highlightedElements.forEach((el) => {
el.removeAttribute("browser-user-highlight-id");
});
// Remove any highlight overlays
const overlays = document.querySelectorAll(
'div[style*="position: absolute"][style*="z-index: 999999"]'
);
overlays.forEach((overlay) => overlay.remove());
// Remove any debug screenshot overlays
const debugOverlays = document.querySelectorAll(
'div[style*="position: fixed"][style*="z-index: 10000"]'
);
debugOverlays.forEach((overlay) => overlay.remove());
// Remove any click indicators
const indicators = document.querySelectorAll(
'div[style*="position: fixed"][style*="border-radius: 50%"]'
);
indicators.forEach((indicator) => indicator.remove());
// Remove any cursor elements
removeCursor();
// Remove any tooltip elements
const tooltips = document.querySelectorAll('.playwright-tooltip');
tooltips.forEach(tooltip => tooltip.remove());
// Remove any extension-added styles
const extensionStyles = document.querySelectorAll('style[data-extension="playwright"]');
extensionStyles.forEach(style => style.remove());
// Remove any extension-added classes from body
document.body.classList.remove('playwright-hover-mode');
document.body.classList.remove('playwright-highlight-mode');
} catch (error) {
console.error("Error during cleanup:", error);
}
}
function createSelectorMap(elementTree) {
function processNode(node) {
if (node.type === "element") {
// If this node is highlighted, store it
if (typeof node.highlightIndex === "number") {
interactiveElementsMap[node.highlightIndex] = node;
}
// Continue traversing children
if (Array.isArray(node.children)) {
node.children.forEach((child) => processNode(child));
}
}
// Text nodes, or other node types, we do nothing special here
}
processNode(elementTree);
return interactiveElementsMap;
}
function parseNode(nodeData, parent = null) {
// Validate input
if (!nodeData || typeof nodeData !== 'object') {
return null;
}
try {
// Handle text nodes
if (nodeData.type === 'TEXT_NODE' || nodeData.type === 'text') {
if (typeof nodeData.text !== 'string') {
console.warn('Text node missing valid text content');
return null;
}
return {
type: 'text',
text: nodeData.text.trim(), // Trim whitespace
isVisible: Boolean(nodeData.isVisible),
parent: parent,
};
}
// Handle element nodes
if (!nodeData.tagName) {
return null;
}
const elementNode = {
type: 'element',
tagName: nodeData.tagName,
xpath: nodeData.xpath || '',
attributes: nodeData.attributes || {},
isVisible: Boolean(nodeData.isVisible),
isInteractive: Boolean(nodeData.isInteractive),
isTopElement: Boolean(nodeData.isTopElement),
highlightIndex: typeof nodeData.highlightIndex === 'number' ? nodeData.highlightIndex : null,
shadowRoot: Boolean(nodeData.shadowRoot),
children: [], // Initialize empty array
parent: parent,
};
// Recursively parse children if they exist
if (Array.isArray(nodeData.children)) {
elementNode.children = nodeData.children
.map(child => parseNode(child, elementNode)) // Use regular function call instead of this
.filter(child => child !== null); // Filter out invalid children
}
return elementNode;
} catch (error) {
console.error('Error parsing node:', error);
return null;
}
}
// Function to get the list of interactive elements
function getInteractiveElementsList(rootNode) {
const parsedNode = parseNode(rootNode);
createSelectorMap(parsedNode);
console.log("Interactive Elements List:", interactiveElementsMap);
return parsedNode;
}
function hasParentWithHighlightIndex(node) {
let current = node.parent;
while (current) {
if (typeof current.highlightIndex === "number") {
// If it's an integer or numeric, we treat that as having a highlight
return true;
}
current = current.parent;
}
return false;
}
function getAllTextTillNextClickableElement(node) {
const textParts = [];
function collectText(currentNode) {
// If we hit a different element that is highlighted, stop recursion down that branch
if (
currentNode !== node &&
currentNode.type === "element" &&
typeof currentNode.highlightIndex === "number"
) {
return;
}
// If it's a text node, collect its text
if (currentNode.type === "text") {
textParts.push(currentNode.text);
}
// If it's an element node, keep recursing into its children
else if (currentNode.type === "element" && currentNode.children) {
currentNode.children.forEach((child) => collectText(child));
}
}
collectText(node);
return textParts.join("\n").trim();
}
function clickableElementsToString(rootNode, includeAttributes = []) {
const lines = [];
function processNode(node) {
if (node.type === "element") {
// If this element is explicitly highlighted (i.e. has highlightIndex)
if (typeof node.highlightIndex === "number") {
// Build an attributes string (only for keys in includeAttributes)
let attrStr = "";
if (includeAttributes.length > 0) {
const filteredAttrs = Object.entries(node.attributes)
.filter(([key]) => includeAttributes.includes(key))
.map(([key, value]) => `${key}="${value}"`)
.join(" ");
if (filteredAttrs.length > 0) {
attrStr = " " + filteredAttrs; // prepend a space
}
}
// Gather text under this node until another clickable element is found
const innerText = getAllTextTillNextClickableElement(node);
// e.g. "12[:]<button id="myBtn">Some text</button>"
lines.push(
`${node.highlightIndex}[:]<${node.tagName}${attrStr}>${innerText}</${node.tagName}>`
);
}
// Regardless of highlight, process children to find more clickable elements or text
if (node.children && node.children.length > 0) {
node.children.forEach((child) => processNode(child));
}
} else if (node.type === "text") {
// Only include this text if it doesn't live under a highlighted ancestor
// (this matches the "if not node.has_parent_with_highlight_index()" in Python)
// if (!hasParentWithHighlightIndex(node)) {
// }
lines.push(`_[:]${node.text}`);
}
}
processNode(rootNode);
return lines.join("\n");
}
// Add fill handler function
async function handleFill(elementData, value) {
try {
if (!elementData) {
console.error("No element data provided");
return false;
}
const element = getLocateElement(elementData);
console.log("Filling element:", element);
if (!element) {
console.warn(`Element not found with selector: ${elementData.xpath}`);
return false;
}
// Get element center coordinates for visual feedback
const rect = element.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
// Highlight the element
const originalOutline = element.style.outline;
element.style.outline = "2px solid blue";
try {
// Wait for cursor animation to complete
await animateCursorTo(x, y);
// Show click indicator and wait for animation
await new Promise(resolve => {
showClickIndicator(x, y, "#3399FF");
setTimeout(resolve, 500);
});
// Focus the element and wait for focus events
element.focus();
await new Promise(resolve => setTimeout(resolve, 100));
element.dispatchEvent(new Event("focus", { bubbles: true, composed: true }));
await new Promise(resolve => setTimeout(resolve, 100));
// Clear existing value if it's an input or textarea
if (element.tagName === "INPUT" || element.tagName === "TEXTAREA") {
element.value = "";
element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
await new Promise(resolve => setTimeout(resolve, 100));
}
// Type the value character by character with delays
for (const char of value) {
// Create and dispatch keydown event
const keydownEvent = new KeyboardEvent("keydown", {
key: char,
code: `Key${char.toUpperCase()}`,
bubbles: true,
cancelable: true,
composed: true
});
element.dispatchEvent(keydownEvent);
// Create and dispatch keypress event
const keypressEvent = new KeyboardEvent("keypress", {
key: char,
code: `Key${char.toUpperCase()}`,
bubbles: true,
cancelable: true,
composed: true
});
element.dispatchEvent(keypressEvent);
// Update value and dispatch input event
element.value += char;
element.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
// Create and dispatch keyup event
const keyupEvent = new KeyboardEvent("keyup", {
key: char,
code: `Key${char.toUpperCase()}`,
bubbles: true,
cancelable: true,
composed: true
});
element.dispatchEvent(keyupEvent);
// Small delay between characters
await new Promise(resolve => setTimeout(resolve, 50));
}
// Final change event
element.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
// Wait for any input-related animations to complete
await new Promise(resolve => setTimeout(resolve, 500));
// Remove highlight
element.style.outline = originalOutline;
return true;
} catch (error) {
element.style.outline = originalOutline;
throw error;
}
} catch (error) {
console.error("Error in fill handler:", error);
return false;
}
}
// Function to check if document is ready for interaction
function isDocumentReady() {
// Check if document is in complete or interactive state
if (document.readyState !== 'complete' && document.readyState !== 'interactive') {
return false;
}
// Check if any iframes are still loading
const iframes = document.getElementsByTagName('iframe');
for (const iframe of iframes) {
try {
const iframeDoc = iframe.contentDocument;
if (iframeDoc && iframeDoc.readyState !== 'complete') {
return false;
}
} catch (e) {
// Cross-origin iframe, ignore
}
}
// Check if any images are still loading
const images = document.getElementsByTagName('img');
for (const img of images) {
if (!img.complete) {
return false;
}
}
// Check if any dynamic content is still loading (e.g., React, Vue, Angular)
const loadingIndicators = document.querySelectorAll('[aria-busy="true"], [role="progressbar"]');
if (loadingIndicators.length > 0) {
return false;
}
return true;
}
// Function to modify the tab title for active session
function setActiveSessionTitle() {
if (!originalTitle) {
originalTitle = document.title;
}
document.title = `🤖 ${originalTitle}`;
}
// Function to restore the original tab title
function restoreOriginalTitle() {
if (originalTitle) {
document.title = originalTitle;
originalTitle = null;
}
}
// Update the message listener
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
try {
if (message.type === "INIT_CURSOR") {
initializeCursor();
setActiveSessionTitle();
sendResponse({ success: true });
} else if (message.type === "CLEANUP_MARKUP") {
cleanupExtensionMarkup();
restoreOriginalTitle();
sendResponse({ success: true });
} else if (message.type === "SESSION_STATE") {
if (message.state === "active") {
setActiveSessionTitle();
} else {
restoreOriginalTitle();
}
sendResponse({ success: true });
} else if (message.type === "CHECK_DOCUMENT_READY") {
sendResponse({ success: true, ready: isDocumentReady() });
} else if (message.type === "PERFORM_CLICK") {
console.log("Message.index:", message.index);
console.log("Message.index parsed:", parseInt(message.index));
console.log("interactiveElementsMap:", interactiveElementsMap);
const elementData = interactiveElementsMap[parseInt(message.index)];
console.log("elementData:", elementData);
console.log("Attempting to click element:", {
requestedIndex: message.index,
foundElement: elementData,
});
if (!elementData) {
sendResponse({
success: false,
error: `No element found with index: ${message.index}`,
});
return true;
}
handleClick(elementData)
.then((success) => {
sendResponse({ success });
})
.catch((error) => {
console.error("Error performing click:", error);
sendResponse({ success: false, error: error.message });
});
} else if (message.type === "PERFORM_FILL") {
const elementData = interactiveElementsMap[parseInt(message.index)];
console.log("Attempting to fill element:", {
requestedIndex: message.index,
foundElement: elementData,
value: message.value,
});
if (!elementData) {
sendResponse({
success: false,
error: `No element found with index: ${message.index}`,
});
return true;
}
handleFill(elementData, message.value)
.then((success) => {
sendResponse({ success });
})
.catch((error) => {
console.error("Error performing fill:", error);
sendResponse({ success: false, error: error.message });
});
} else if (message.type === "SEARCH_GOOGLE") {
window.location.href = `https://www.google.com/search?q=${encodeURIComponent(
message.query
)}`;
sendResponse({ success: true });
} else if (message.type === "GO_TO_URL") {
window.location.href = message.url;
sendResponse({ success: true });
} else if (message.type === "GO_BACK") {
window.history.back();
sendResponse({ success: true });
} else if (message.type === "SCROLL_DOWN") {
if (message.amount) {
window.scrollBy(0, message.amount);
} else {
document.documentElement.scrollTop += window.innerHeight;
}
sendResponse({ success: true });
} else if (message.type === "SCROLL_UP") {
if (message.amount) {
window.scrollBy(0, -message.amount);
} else {
document.documentElement.scrollTop -= window.innerHeight;
}
sendResponse({ success: true });
} else if (message.type === "SEND_KEYS") {
try {
const activeElement = document.activeElement;
if (
activeElement &&
(activeElement.tagName === "INPUT" ||
activeElement.tagName === "TEXTAREA")
) {
// For special keys like Enter, Backspace, etc.
if (message.keys.includes("+") || message.keys.length > 1) {
const event = new KeyboardEvent("keydown", {
key: message.keys,
code: message.keys,
bubbles: true,
cancelable: true,
composed: true,
});
activeElement.dispatchEvent(event);
} else {
// For regular text input
activeElement.value += message.keys;
activeElement.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
activeElement.dispatchEvent(new Event("change", { bubbles: true, composed: true }));
}
}
sendResponse({ success: true });
} catch (error) {
console.error("Error sending keys:", error);
sendResponse({ success: false, error: error.message });
}
} else if (message.type === "GET_PAGE_MARKUP") {
console.log("Starting page markup analysis...");
// Clean up before getting markup
cleanupExtensionMarkup();
// Reset interactive elements tracking
resetInteractiveElements();
console.log("Reset interactive elements tracking");
// Build the DOM tree and collect interactive elements
try {
doHighlightElements = message.highlightElements || false;
let includeAttributes = [
"title",
"type",
"name",
"role",
"tabindex",
"aria-label",
"placeholder",
"value",
"alt",
"aria-expanded",
];
const domTree = buildDomTree(document.body);
console.log("DOM Tree:", domTree);
const interactiveElements = getInteractiveElementsList(domTree);
console.log(`Found ${interactiveElementsMap.length} interactive elements`);
sendResponse({
success: true,
stringifiedInteractiveElements: clickableElementsToString(interactiveElements, includeAttributes),
});
} catch (error) {
console.error("Error building interactive elements list:", error);
sendResponse({
success: false,
error:
"Failed to build interactive elements list: " + error.message,
});
}
} else if (message.type === "DEBUG_SCREENSHOT") {
// Handle debug screenshot display
const debugOverlay = document.createElement("div");
debugOverlay.style.cssText = `
position: fixed;
top: 10px;
right: 10px;
z-index: 10000;
background: rgba(0, 0, 0, 0.8);
padding: 10px;
border-radius: 5px;
max-width: 300px;
`;
const img = document.createElement("img");
img.src = message.imageUri;
img.style.width = "100%";
debugOverlay.appendChild(img);
document.body.appendChild(debugOverlay);
// Remove after 5 seconds
setTimeout(() => {
debugOverlay.remove();
}, 5000);
sendResponse({ success: true });
}
} catch (error) {
console.error("Error in content script:", error);
sendResponse({ success: false, error: error.message });
}
// Return true to indicate we'll send a response asynchronously
return true;
});
// Create or update the cursor position
function updateCursor(x, y) {
if (!cursorElement) {
cursorElement = document.createElement("div");
// Create the cursor pointer element
const pointer = document.createElement("div");
Object.assign(pointer.style, {
width: "20px",
height: "20px",
position: "absolute",
top: "0",
left: "0",
backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="%23FF5733"><path d="M7 2l12 11.2-5.8.5 3.3 7.3-2.2 1-3.2-7-4.1 4z"/></svg>')`,
backgroundSize: "contain",
backgroundRepeat: "no-repeat",
pointerEvents: "none",
});
// Create the name label
const label = document.createElement("div");
Object.assign(label.style, {
position: "absolute",