Skip to content

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

Fix: filter shadow roots from children nodes, ensuring clean separation in the DOM tree structure. Update EnhancedDOMTreeNode to make a copy of children_nodes to prevent mutation of the original list.

Magnus Müller730019471d4c
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index ef6c16adb..72c4312b8 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -613,7 +613,16 @@ class DomService:
if 'children' in node and node['children']:
dom_tree_node.children_nodes = []
+ # Build set of shadow root node IDs to filter them out from children
+ shadow_root_node_ids = set()
+ if 'shadowRoots' in node and node['shadowRoots']:
+ for shadow_root in node['shadowRoots']:
+ shadow_root_node_ids.add(shadow_root['nodeId'])
+
for child in node['children']:
+ # Skip shadow roots - they should only be in shadow_roots list
+ if child['nodeId'] in shadow_root_node_ids:
+ continue
dom_tree_node.children_nodes.append(
await _construct_enhanced_node(child, updated_html_frames, total_frame_offset)
)
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 72ee8e429..952db8532 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -396,7 +396,8 @@ class EnhancedDOMTreeNode:
"""
Returns all children nodes, including shadow roots
"""
- children = self.children_nodes or []
+ # IMPORTANT: Make a copy to avoid mutating the original children_nodes list!
+ children = list(self.children_nodes) if self.children_nodes else []
if self.shadow_roots:
children.extend(self.shadow_roots)
return children