Skip to content

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

added drag drop action

PaperBoardOfficial6f96453794e7
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 7c3f78b45..f1faa8536 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -3,13 +3,13 @@ import enum
import json
import logging
import re
-from typing import Dict, Generic, Optional, Type, TypeVar
+from typing import Dict, Generic, Optional, Tuple, Type, TypeVar, cast
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import PromptTemplate
# from lmnr.sdk.laminar import Laminar
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser.context import BrowserContext
@@ -21,11 +21,13 @@ from browser_use.controller.views import (
ClickElementByXpathAction,
CloseTabAction,
DoneAction,
+ DragDropAction,
GoToUrlAction,
GroupTabsAction,
InputTextAction,
NoParamsAction,
OpenTabAction,
+ Position,
ScrollAction,
SearchGoogleAction,
SendKeysAction,
@@ -33,6 +35,9 @@ from browser_use.controller.views import (
UngroupTabsAction,
)
from browser_use.utils import time_execution_sync
+from playwright.async_api import BrowserContext as PlaywrightBrowserContext, Page, ElementHandle, Locator
+from playwright.async_api import Position as PlaywrightPosition
+from playwright.async_api import Error as PlaywrightError
logger = logging.getLogger(__name__)
@@ -552,6 +557,220 @@ class Controller(Generic[Context]):
logger.error(msg)
return ActionResult(error=msg, include_in_memory=True)
+ @self.registry.action(
+ 'Drag and drop elements or between coordinates on the page - useful for canvas drawing, sortable lists, sliders, file uploads, and UI rearrangement',
+ param_model=DragDropAction,
+ )
+ async def drag_drop(params: DragDropAction, browser: BrowserContext) -> ActionResult:
+ """
+ Performs a precise drag and drop operation between elements or coordinates.
+ """
+ async def get_drag_elements(
+ page: Page,
+ source_selector: str,
+ target_selector: str,
+ ) -> Tuple[Optional[ElementHandle], Optional[ElementHandle]]:
+ """Get source and target elements with appropriate error handling."""
+ source_element = None
+ target_element = None
+
+ try:
+ # page.locator() auto-detects CSS and XPath
+ source_locator = page.locator(source_selector)
+ target_locator = page.locator(target_selector)
+
+ # Check if elements exist
+ source_count = await source_locator.count()
+ target_count = await target_locator.count()
+
+ if source_count > 0:
+ source_element = await source_locator.first.element_handle()
+ logger.debug(f"Found source element with selector: {source_selector}")
+ else:
+ logger.warning(f"Source element not found: {source_selector}")
+
+ if target_count > 0:
+ target_element = await target_locator.first.element_handle()
+ logger.debug(f"Found target element with selector: {target_selector}")
+ else:
+ logger.warning(f"Target element not found: {target_selector}")
+
+ except Exception as e:
+ logger.error(f"Error finding elements: {str(e)}")
+
+ return source_element, target_element
+
+ async def get_element_coordinates(
+ source_element: ElementHandle,
+ target_element: ElementHandle,
+ source_position: Optional[Position],
+ target_position: Optional[Position]
+ ) -> Tuple[Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
+ """Get coordinates from elements with appropriate error handling."""
+ source_coords = None
+ target_coords = None
+
+ try:
+ # Get source coordinates
+ if source_position:
+ source_coords = (source_position.x, source_position.y)
+ else:
+ source_box = await source_element.bounding_box()
+ if source_box:
+ source_coords = (
+ int(source_box["x"] + source_box["width"] / 2),
+ int(source_box["y"] + source_box["height"] / 2)
+ )
+
+ # Get target coordinates
+ if target_position:
+ target_coords = (target_position.x, target_position.y)
+ else:
+ target_box = await target_element.bounding_box()
+ if target_box:
+ target_coords = (
+ int(target_box["x"] + target_box["width"] / 2),
+ int(target_box["y"] + target_box["height"] / 2)
+ )
+ except Exception as e:
+ logger.error(f"Error getting element coordinates: {str(e)}")
+
+ return source_coords, target_coords
+
+ async def execute_drag_operation(
+ page: Page,
+ source_x: int,
+ source_y: int,
+ target_x: int,
+ target_y: int,
+ steps: int,
+ delay_ms: int,
+ ) -> Tuple[bool, str]:
+ """Execute the drag operation with comprehensive error handling."""
+ try:
+ # Try to move to source position
+ try:
+ await page.mouse.move(source_x, source_y)
+ logger.debug(f"Moved to source position ({source_x}, {source_y})")
+ except Exception as e:
+ logger.error(f"Failed to move to source position: {str(e)}")
+ return False, f"Failed to move to source position: {str(e)}"
+
+ # Press mouse button down
+ await page.mouse.down()
+
+ # Move to target position with intermediate steps
+ for i in range(1, steps + 1):
+ ratio = i / steps
+ intermediate_x = int(source_x + (target_x - source_x) * ratio)
+ intermediate_y = int(source_y + (target_y - source_y) * ratio)
+
+ await page.mouse.move(intermediate_x, intermediate_y)
+
+ if delay_ms > 0:
+ await asyncio.sleep(delay_ms / 1000)
+
+ # Move to final target position
+ await page.mouse.move(target_x, target_y)
+
+ # Move again to ensure dragover events are properly triggered
+ await page.mouse.move(target_x, target_y)
+
+ # Release mouse button
+ await page.mouse.up()
+
+ return True, "Drag operation completed successfully"
+
+ except Exception as e:
+ return False, f"Error during drag operation: {str(e)}"
+
+ page = await browser.get_current_page()
+
+ try:
+ # Initialize variables
+ source_x: Optional[int] = None
+ source_y: Optional[int] = None
+ target_x: Optional[int] = None
+ target_y: Optional[int] = None
+
+ # Normalize parameters
+ steps = max(1, params.steps or 10)
+ delay_ms = max(0, params.delay_ms or 5)
+
+ # Case 1: Element selectors provided
+ if params.element_source and params.element_target:
+ logger.debug(f"Using element-based approach with selectors")
+
+ source_element, target_element = await get_drag_elements(
+ page,
+ params.element_source,
+ params.element_target,
+ )
+
+ if not source_element or not target_element:
+ error_msg = f"Failed to find {'source' if not source_element else 'target'} element"
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ source_coords, target_coords = await get_element_coordinates(
+ source_element,
+ target_element,
+ params.element_source_offset,
+ params.element_target_offset
+ )
+
+ if not source_coords or not target_coords:
+ error_msg = f"Failed to determine {'source' if not source_coords else 'target'} coordinates"
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ source_x, source_y = source_coords
+ target_x, target_y = target_coords
+
+ # Case 2: Coordinates provided directly
+ elif all(coord is not None for coord in [params.coord_source_x, params.coord_source_y, params.coord_target_x, params.coord_target_y]):
+ logger.debug(f"Using coordinate-based approach")
+ source_x = params.coord_source_x
+ source_y = params.coord_source_y
+ target_x = params.coord_target_x
+ target_y = params.coord_target_y
+ else:
+ error_msg = "Must provide either source/target selectors or source/target coordinates"
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ # Validate coordinates
+ if any(coord is None for coord in [source_x, source_y, target_x, target_y]):
+ error_msg = "Failed to determine source or target coordinates"
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ # Perform the drag operation
+ success, message = await execute_drag_operation(
+ page,
+ cast(int, source_x),
+ cast(int, source_y),
+ cast(int, target_x),
+ cast(int, target_y),
+ steps,
+ delay_ms,
+ )
+
+ if not success:
+ logger.error(f"Drag operation failed: {message}")
+ return ActionResult(error=message, include_in_memory=True)
+
+ # Create descriptive message
+ if params.element_source and params.element_target:
+ msg = f"🖱️ Dragged element '{params.element_source}' to '{params.element_target}'"
+ else:
+ msg = f"🖱️ Dragged from ({source_x}, {source_y}) to ({target_x}, {target_y})"
+
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
+
+ except Exception as e:
+ error_msg = f"Failed to perform drag and drop: {str(e)}"
+ logger.error(error_msg)
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+
# Register ---------------------------------------------------------------
def action(self, description: str, **kwargs):
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 31c3bd833..15c0dd291 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -86,3 +86,24 @@ class NoParamsAction(BaseModel):
# If you want to silently allow unknown fields at top-level,
# set extra = 'allow' as well:
extra = 'allow'
+
+class Position(BaseModel):
+ x: int
+ y: int
+
+class DragDropAction(BaseModel):
+ # Element-based approach
+ element_source: Optional[str] = Field(None, description="CSS selector or XPath of the element to drag from")
+ element_target: Optional[str] = Field(None, description="CSS selector or XPath of the element to drop onto")
+ element_source_offset: Optional[Position] = Field(None, description="Precise position within the source element to start drag (in pixels from top-left corner)")
+ element_target_offset: Optional[Position] = Field(None, description="Precise position within the target element to drop (in pixels from top-left corner)")
+
+ # Coordinate-based approach (used if selectors not provided)
+ coord_source_x: Optional[int] = Field(None, description="Absolute X coordinate on page to start drag from (in pixels)")
+ coord_source_y: Optional[int] = Field(None, description="Absolute Y coordinate on page to start drag from (in pixels)")
+ coord_target_x: Optional[int] = Field(None, description="Absolute X coordinate on page to drop at (in pixels)")
+ coord_target_y: Optional[int] = Field(None, description="Absolute Y coordinate on page to drop at (in pixels)")
+
+ # Common options
+ steps: Optional[int] = Field(10, description="Number of intermediate points for smoother movement (5-20 recommended)")
+ delay_ms: Optional[int] = Field(5, description="Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)")
diff --git a/examples/features/drag_drop.py b/examples/features/drag_drop.py
new file mode 100644
index 000000000..074bbfa88
--- /dev/null
+++ b/examples/features/drag_drop.py
@@ -0,0 +1,47 @@
+import asyncio
+import os
+
+from dotenv import load_dotenv
+from langchain_google_genai import ChatGoogleGenerativeAI
+from pydantic import SecretStr
+
+from browser_use import Agent
+
+
+load_dotenv()
+api_key = os.getenv('GEMINI_API_KEY')
+if not api_key:
+ raise ValueError('GEMINI_API_KEY is not set')
+
+llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))
+
+
+task_1 = """
+Navigate to: https://sortablejs.github.io/Sortable/.
+Then scroll down to the first examplw with title "Simple list example".
+Drag the element with name "item 1" to below the element with name "item 3".
+"""
+
+
+task_2 = """
+Navigate to: https://excalidraw.com/.
+Click on the pencil icon (with index 40).
+Then draw a triangle in the canvas.
+Draw the triangle starting from coordinate (400,400).
+You can use the drag and drop action to draw the triangle.
+"""
+
+
+async def run_search():
+ agent = Agent(
+ task=task_1,
+ llm=llm,
+ max_actions_per_step=1,
+ use_vision=True,
+ )
+
+ await agent.run(max_steps=25)
+
+
+if __name__ == '__main__':
+ asyncio.run(run_search())