Skip to content

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

Refactor HTMLSerializer to prioritize serialization of shadow roots before light DOM children, improving support for declarative shadow DOM and slot projection.

Magnus Müller963e26bde677
diff --git a/browser_use/dom/serializer/html_serializer.py b/browser_use/dom/serializer/html_serializer.py
index 3715bc72f..afddf3604 100644
--- a/browser_use/dom/serializer/html_serializer.py
+++ b/browser_use/dom/serializer/html_serializer.py
@@ -111,8 +111,15 @@ class HTMLSerializer:
if child_html:
parts.append(child_html)
else:
- # Process children and shadow roots
- for child in node.children_and_shadow_roots:
+ # Serialize shadow roots FIRST (for declarative shadow DOM)
+ if node.shadow_roots:
+ for shadow_root in node.shadow_roots:
+ child_html = self.serialize(shadow_root, depth + 1)
+ if child_html:
+ parts.append(child_html)
+
+ # Then serialize light DOM children (for slot projection)
+ for child in node.children:
child_html = self.serialize(child, depth + 1)
if child_html:
parts.append(child_html)