Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
open cross-origin iframes in new tabs and mark their titles
Nick Sweetingf524540d9493
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 322ab7827..eb3fb046f 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -784,6 +784,21 @@ class BrowserContext:highlight_elements=self.config.highlight_elements,)+ tabs_info = await self.get_tabs_info()++ # Get all cross-origin iframes within the page and open them in new tabs+ # mark the titles of the new tabs so the LLM knows to check them for additional content+ iframe_urls = await dom_service.get_cross_origin_iframes()+ for url in iframe_urls:+ await self.create_new_tab(url)+ tabs_info.append(+ TabInfo(+ page_id=tabs_info[-1].page_id + 1,+ url=url,+ title=f'Popup opened by page: {page.url}',+ )+ )+screenshot_b64 = await self.take_screenshot()pixels_above, pixels_below = await self.get_scroll_info(page)@@ -792,7 +807,7 @@ class BrowserContext:selector_map=content.selector_map,url=page.url,title=await page.title(),- tabs=await self.get_tabs_info(),+ tabs=tabs_info,screenshot=screenshot_b64,pixels_above=pixels_above,pixels_below=pixels_below,diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex f0bd1a413..c34429d92 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -3,7 +3,8 @@ import jsonimport loggingfrom dataclasses import dataclassfrom importlib import resources-from typing import TYPE_CHECKING, Optional, TypeVar+from typing import TYPE_CHECKING, Optional+from urllib.parse import urlparseif TYPE_CHECKING:from playwright.async_api import Page@@ -26,95 +27,6 @@ class ViewportInfo:height: int-T = TypeVar('T', dict, list, int)---def merge_dom_trees(value_a: T, value_b: T) -> T:- """merge two buildDomTree.js result dicts. used to put together results from parent frame and child cross-origin iframes"""-- if isinstance(value_a, dict) and isinstance(value_b, dict):- merged_tree = value_a.copy()- for key, value in value_b.items():- if key == 'rootId':- # original top parent rootId should never change- continue-- if key in merged_tree:- merged_tree[key] = merge_dom_trees(merged_tree[key], value)- else:- merged_tree[key] = value-- return merged_tree-- elif isinstance(value_a, list) and isinstance(value_b, list):- merged_tree = value_a.copy()- for value in value_b:- if value not in merged_tree:- merged_tree.append(value)-- return merged_tree-- elif isinstance(value_a, (int, float)) and isinstance(value_b, (int, float)):- # assumes all numeric values in perf metrics are summable totals counts or seconds/milliseconds- # may not always be true in the future, e.g. if we add any avg values then naiive sum will be wrong- return value_a + value_b-- elif isinstance(value_a, str) and isinstance(value_b, str):- if value_a == value_b:- return value_a-- raise TypeError(f'Cannot merge {type(value_a)}: {value_a} and {type(value_b)}: {value_b}')---def link_cross_origin_iframes(eval_page: dict) -> dict:- """link cross-origin iframes to their parent frame"""- for node in eval_page['map'].values():- if node['tagName'] == 'iframe' and not node['children']:- # locate the child frame's body and put it in the children- # so that it's handled the same as a same-origin iframe- for elem in eval_page['map'].values():- if elem.get('parentFrameId') == node['id']:- node['children'].append(elem)- break-- return eval_page---def dump_frame_tree(frame, indent=''):- """From: https://playwright.dev/python/docs/api/class-frame"""- yield (indent + frame.name + '@' + frame.url)- for child in frame.child_frames:- yield from dump_frame_tree(child, indent + ' ')---# def find_nested_iframes(root_frame) -> dict[str, 'Frame']:-# """-# iteratively find all iframes in the page-# assumptions:-# - iframes can be nested-# - iframes can be cross-origin-iframes-# - non-cross-origin iframes can nested inside cross-origin iframes-# - iframes arent guaranteed to have any id, name, or unique src url-# - iframes and their content can be added/removed/updated multiple times per second by JS-# """--# frame_idx = 0--# all_frames = {f'{frame_idx}': root_frame}-# frames_to_search = [list(all_frames.keys())[0]]-# while frames_to_search:-# frame_idx += 1-# frame_id = frames_to_search.pop()-# frame = all_frames[frame_id]--# for child_frame in frame.child_frames if hasattr(frame, 'child_frames') else frame.frames:-# child_frame_id = f'{frame_id}/{frame_idx}'-# all_frames[child_frame_id] = child_frame-# frames_to_search.append(child_frame_id)--# return all_frames--class DomService:def __init__(self, page: 'Page'):self.page = page@@ -133,6 +45,14 @@ class DomService:element_tree, selector_map = await self._build_dom_tree(highlight_elements, focus_element, viewport_expansion)return DOMState(element_tree=element_tree, selector_map=selector_map)+ @time_execution_async('--get_cross_origin_iframes')+ async def get_cross_origin_iframes(self) -> list[str]:+ return [+ frame.url+ for frame in self.page.frames+ if urlparse(frame.url).netloc != urlparse(self.page.url).netloc and not frame.url.startswith('data:')+ ]+@time_execution_async('--build_dom_tree')async def _build_dom_tree(self,@@ -168,53 +88,12 @@ class DomService:'debugMode': debug_mode,}- logger.debug('Running buildDomTree.js on: %s', self.page.url)-- # 1. recursively find all nested iframes- # 2. filter to only include cross-origin iframes- # 3. run buildDomTree.js on all cross-origin iframes + top-level-page in parallel- # 4. merge the results into a single flat selector_map-- print(list(dump_frame_tree(self.page.main_frame)))-try:eval_page: dict = await self.page.evaluate(self.js_code, args)except Exception as e:logger.error('Error evaluating JavaScript: %s', e)raise- # # also run buildDomTree.js on all cross-origin iframes- # inner_iframes = [- # await frame.frame_element()- # for frame in self.page.frames- # if frame.url != self.page.url and not frame.url.startswith('data:')- # ]- # for frame in inner_iframes:- # try:- # # check if the frame already has a buildDomTree.js- # inner_target = await frame.content_frame()- # has_built_dom_tree = await inner_target.evaluate('window._loadedBrowserUseBuildDomTree')- # if has_built_dom_tree:- # # was already processed by buildDomTree.js's iframe-traveral handling- # continue- # else:- # logger.debug('Found cross-origin iframe that needs special handling: %s', inner_target.url)- # # start the index offset from the last index of the parent frame so that child element idx dont conflict- # iframe_args = {- # **args,- # 'indexOffset': len(eval_page['map']),- # 'parentFrameId': frame.parent_frame_id,- # }- # iframe_results: dict = await inner_target.evaluate(self.js_code, iframe_args)- # eval_page: dict = merge_dom_trees(eval_page, iframe_results)-- # except Exception as e:- # logger.error('Error checking page for cross origin iframes: %s', e)- # # frames often dissapear upon navigation, page changes, etc. no need to hard fail here- # continue-- # eval_page = link_cross_origin_iframes(eval_page)-# Only log performance metrics in debug modeif debug_mode and 'perfMetrics' in eval_page:logger.debug('DOM Tree Building Performance Metrics:\n%s', json.dumps(eval_page['perfMetrics'], indent=2))