Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Add caching for client rects and improve highlight cleanup logic

satya-nutellac6016b7cc261
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index 2919ce6ab..aa03e30e9 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -51,6 +51,8 @@
boundingRectHitRate: 0,
computedStyleHitRate: 0,
overallHitRate: 0,
+ clientRectsCacheHits: 0,
+ clientRectsCacheMisses: 0,
},
nodeMetrics: {
totalNodes: 0,
@@ -102,9 +104,11 @@
// Add caching mechanisms at the top level
const DOM_CACHE = {
boundingRects: new WeakMap(),
+ clientRects: new WeakMap(),
computedStyles: new WeakMap(),
clearCache: () => {
DOM_CACHE.boundingRects = new WeakMap();
+ DOM_CACHE.clientRects = new WeakMap();
DOM_CACHE.computedStyles = new WeakMap();
}
};
@@ -176,6 +180,29 @@
return style;
}
+ // Add a new function to get cached client rects
+ function getCachedClientRects(element) {
+ if (!element) return null;
+
+ if (DOM_CACHE.clientRects.has(element)) {
+ if (debugMode && PERF_METRICS) {
+ PERF_METRICS.cacheMetrics.clientRectsCacheHits++;
+ }
+ return DOM_CACHE.clientRects.get(element);
+ }
+
+ if (debugMode && PERF_METRICS) {
+ PERF_METRICS.cacheMetrics.clientRectsCacheMisses++;
+ }
+
+ const rects = element.getClientRects();
+
+ if (rects) {
+ DOM_CACHE.clientRects.set(element, rects);
+ }
+ return rects;
+ }
+
/**
* Hash map of DOM nodes indexed by their highlight index.
*
@@ -187,17 +214,33 @@
const HIGHLIGHT_CONTAINER_ID = "playwright-highlight-container";
+ // Add a WeakMap cache for XPath strings
+ const xpathCache = new WeakMap();
+
+ // Initialize once and reuse
+ const viewportObserver = new IntersectionObserver(
+ (entries) => {
+ entries.forEach(entry => {
+ elementVisibilityMap.set(entry.target, entry.isIntersecting);
+ });
+ },
+ { rootMargin: `${viewportExpansion}px` }
+ );
+
/**
* Highlights an element in the DOM and returns the index of the next element.
*/
function highlightElement(element, index, parentIframe = null) {
+ pushTiming('highlighting');
+
if (!element) return index;
// Store overlays and the single label for updating
const overlays = [];
let label = null;
- let labelWidth = 20; // Approximate label width
- let labelHeight = 16; // Approximate label height
+ let labelWidth = 20;
+ let labelHeight = 16;
+ let cleanupFn = null;
try {
// Create or get highlight container
@@ -248,6 +291,9 @@
iframeOffset.y = iframeRect.top;
}
+ // Create fragment to hold overlay elements
+ const fragment = document.createDocumentFragment();
+
// Create highlight overlays for each client rect
for (const rect of rects) {
if (rect.width === 0 || rect.height === 0) continue; // Skip empty rects
@@ -267,7 +313,7 @@
overlay.style.width = `${rect.width}px`;
overlay.style.height = `${rect.height}px`;
- container.appendChild(overlay);
+ fragment.appendChild(overlay);
overlays.push({ element: overlay, initialRect: rect }); // Store overlay and its rect
}
@@ -307,7 +353,7 @@
label.style.top = `${labelTop}px`;
label.style.left = `${labelLeft}px`;
- container.appendChild(label);
+ fragment.appendChild(label);
// Update positions on scroll/resize
const updatePositions = () => {
@@ -373,15 +419,53 @@
}
};
- window.addEventListener('scroll', updatePositions, true); // Use capture phase
- window.addEventListener('resize', updatePositions);
-
- // TODO: Add cleanup logic to remove listeners and elements when done.
+ const throttleFunction = (func, delay) => {
+ let lastCall = 0;
+ return (...args) => {
+ const now = performance.now();
+ if (now - lastCall < delay) return;
+ lastCall = now;
+ return func(...args);
+ };
+ };
+ const throttledUpdatePositions = throttleFunction(updatePositions, 16); // ~60fps
+ window.addEventListener('scroll', throttledUpdatePositions, true);
+ window.addEventListener('resize', throttledUpdatePositions);
+
+ // Add cleanup function
+ cleanupFn = () => {
+ window.removeEventListener('scroll', throttledUpdatePositions, true);
+ window.removeEventListener('resize', throttledUpdatePositions);
+ // Remove overlay elements if needed
+ overlays.forEach(overlay => overlay.element.remove());
+ if (label) label.remove();
+ };
+
+ // Then add fragment to container in one operation
+ container.appendChild(fragment);
+
return index + 1;
} finally {
- // popTiming('highlighting'); // Assuming this was a typo and should be removed or corrected
+ popTiming('highlighting');
+ // Store cleanup function for later use
+ if (cleanupFn) {
+ // Keep a reference to cleanup functions in a global array
+ (window._highlightCleanupFunctions = window._highlightCleanupFunctions || []).push(cleanupFn);
+ }
+ }
+ }
+
+ // Add this function to perform cleanup when needed
+ function cleanupHighlights() {
+ if (window._highlightCleanupFunctions && window._highlightCleanupFunctions.length) {
+ window._highlightCleanupFunctions.forEach(fn => fn());
+ window._highlightCleanupFunctions = [];
}
+
+ // Also remove the container
+ const container = document.getElementById(HIGHLIGHT_CONTAINER_ID);
+ if (container) container.remove();
}
function getElementPosition(currentElement) {
@@ -406,6 +490,8 @@
* Returns an XPath tree string for an element.
*/
function getXPathTree(element, stopAtBoundary = true) {
+ if (xpathCache.has(element)) return xpathCache.get(element);
+
const segments = [];
let currentElement = element;
@@ -427,7 +513,9 @@
currentElement = currentElement.parentNode;
}
- return segments.join("/");
+ const result = segments.join("/");
+ xpathCache.set(element, result);
+ return result;
}
/**
@@ -473,15 +561,14 @@
if (!parentElement) return false;
try {
- return isInViewport && parentElement.checkVisibility({
+ return parentElement.checkVisibility({
checkOpacity: true,
checkVisibilityCSS: true,
});
} catch (e) {
// Fallback if checkVisibility is not supported
const style = window.getComputedStyle(parentElement);
- return isInViewport &&
- style.display !== 'none' &&
+ return style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0';
}
@@ -541,6 +628,10 @@
return false;
}
+ // Cache the tagName and style lookups
+ const tagName = element.tagName.toLowerCase();
+ const style = getCachedComputedStyle(element);
+
// Define interactive cursors
const interactiveCursors = new Set([
'pointer', // Link/clickable elements
@@ -590,7 +681,6 @@
function doesElementHaveInteractivePointer(element) {
if (element.tagName.toLowerCase() === "html") return false;
- const style = getCachedComputedStyle(element);
if (interactiveCursors.has(style.cursor)) return true;
@@ -634,9 +724,7 @@
]);
// handle inputs, select, checkbox, radio, textarea, button and make sure they are not cursor style disabled/not-allowed
- if (interactiveElements.has(element.tagName.toLowerCase())) {
- const style = getCachedComputedStyle(element);
-
+ if (interactiveElements.has(tagName)) {
// Check for non-interactive cursor
if (nonInteractiveCursors.has(style.cursor)) {
return false;
@@ -669,7 +757,6 @@
return true;
}
- const tagName = element.tagName.toLowerCase();
const role = element.getAttribute("role");
const ariaRole = element.getAttribute("aria-role");
@@ -747,7 +834,7 @@
* Checks if an element is the topmost element at its position.
*/
function isTopElement(element) {
- const rects = element.getClientRects(); // Use getClientRects
+ const rects = getCachedClientRects(element); // Replace element.getClientRects()
if (!rects || rects.length === 0) {
return false; // No geometry, cannot be top
@@ -827,8 +914,6 @@
* Checks if an element is within the expanded viewport.
*/
function isInExpandedViewport(element, viewportExpansion) {
- return true
-
if (viewportExpansion === -1) {
return true;
}
@@ -1039,6 +1124,13 @@
* Creates a node data object for a given node and its descendants.
*/
function buildDomTree(node, parentIframe = null, isParentHighlighted = false) {
+ // Fast rejection checks first
+ if (!node || node.id === HIGHLIGHT_CONTAINER_ID ||
+ (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)) {
+ if (debugMode) PERF_METRICS.nodeMetrics.skippedNodes++;
+ return null;
+ }
+
if (debugMode) PERF_METRICS.nodeMetrics.totalNodes++;
if (!node || node.id === HIGHLIGHT_CONTAINER_ID) {