Skip to main content

Handles

Introduction​

Playwright can create handles to the page DOM elements or any other objects inside the page. These handles live in the Playwright process, whereas the actual objects live in the browser. There are two types of handles:

  • JSHandle to reference any JavaScript objects in the page
  • ElementHandle to reference DOM elements in the page, it has extra methods that allow performing actions on the elements and asserting their properties.

Since any DOM element in the page is also a JavaScript object, any ElementHandle is a JSHandle as well.

Handles are used to perform operations on those actual objects in the page. You can evaluate on a handle, get handle properties, pass handle as an evaluation parameter, serialize page object into JSON etc. See the JSHandle class API for these and methods.

API reference​

Here is the easiest way to obtain a JSHandle.

js_handle = page.evaluate_handle('window')
# Use jsHandle for evaluations.

Element Handles​

Discouraged

The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.

When ElementHandle is required, it is recommended to fetch it with the page.wait_for_selector() or frame.wait_for_selector() methods. These APIs wait for the element to be attached and visible.

# Get the element handle
element_handle = page.wait_for_selector('#box')

# Assert bounding box for the element
bounding_box = element_handle.bounding_box()
assert bounding_box["width"] == 100

# Assert attribute for the element
class_names = element_handle.get_attribute('class')
assert 'highlighted' in class_names