1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// ElementHandle protocol object
//
// Represents a DOM element in the page. Supports element-specific operations like screenshots.
// ElementHandles are created via query_selector methods and are protocol objects with GUIDs.
use crate::error::Result;
use crate::protocol::locator::BoundingBox;
use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
use base64::Engine;
use serde::Deserialize;
use serde_json::Value;
use std::any::Any;
use std::sync::Arc;
/// ElementHandle represents a DOM element in the page.
///
/// ElementHandles are created via `page.query_selector()` or `frame.query_selector()`.
/// They are protocol objects that allow element-specific operations like taking screenshots.
///
/// See: <https://playwright.dev/docs/api/class-elementhandle>
#[derive(Clone)]
pub struct ElementHandle {
base: ChannelOwnerImpl,
}
impl ElementHandle {
/// Creates a new ElementHandle from protocol initialization
///
/// This is called by the object factory when the server sends a `__create__` message
/// for an ElementHandle object.
pub fn new(
parent: Arc<dyn ChannelOwner>,
type_name: String,
guid: Arc<str>,
initializer: Value,
) -> Result<Self> {
let base = ChannelOwnerImpl::new(
ParentOrConnection::Parent(parent),
type_name,
guid,
initializer,
);
Ok(Self { base })
}
/// Takes a screenshot of the element and returns the image bytes.
///
/// The screenshot is captured as PNG by default.
///
/// # Example
///
/// ```ignore
/// # use playwright_rs::protocol::Playwright;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let playwright = Playwright::launch().await?;
/// let browser = playwright.chromium().launch().await?;
/// let page = browser.new_page().await?;
/// page.goto("https://example.com", None).await?;
///
/// let element = page.query_selector("h1").await?.expect("h1 not found");
/// let screenshot_bytes = element.screenshot(None).await?;
/// # Ok(())
/// # }
/// ```
///
/// See: <https://playwright.dev/docs/api/class-elementhandle#element-handle-screenshot>
pub async fn screenshot(
&self,
options: Option<crate::protocol::ScreenshotOptions>,
) -> Result<Vec<u8>> {
let params = if let Some(opts) = options {
opts.to_json()
} else {
// Default to PNG with required timeout
serde_json::json!({
"type": "png",
"timeout": crate::DEFAULT_TIMEOUT_MS
})
};
#[derive(Deserialize)]
struct ScreenshotResponse {
binary: String,
}
let response: ScreenshotResponse = self.base.channel().send("screenshot", params).await?;
// Decode base64 to bytes
let bytes = base64::prelude::BASE64_STANDARD
.decode(&response.binary)
.map_err(|e| {
crate::error::Error::ProtocolError(format!(
"Failed to decode element screenshot: {}",
e
))
})?;
Ok(bytes)
}
/// Returns the bounding box of this element, or None if it is not visible.
///
/// The bounding box is in pixels, relative to the top-left corner of the page.
///
/// See: <https://playwright.dev/docs/api/class-elementhandle#element-handle-bounding-box>
pub async fn bounding_box(&self) -> Result<Option<BoundingBox>> {
#[derive(Deserialize)]
struct BoundingBoxResponse {
value: Option<BoundingBox>,
}
let response: BoundingBoxResponse = self
.base
.channel()
.send(
"boundingBox",
serde_json::json!({
"timeout": crate::DEFAULT_TIMEOUT_MS
}),
)
.await?;
Ok(response.value)
}
/// Scrolls this element into the viewport if it is not already visible.
///
/// See: <https://playwright.dev/docs/api/class-elementhandle#element-handle-scroll-into-view-if-needed>
pub async fn scroll_into_view_if_needed(&self) -> Result<()> {
self.base
.channel()
.send_no_result(
"scrollIntoViewIfNeeded",
serde_json::json!({
"timeout": crate::DEFAULT_TIMEOUT_MS
}),
)
.await
}
}
impl ChannelOwner for ElementHandle {
fn guid(&self) -> &str {
self.base.guid()
}
fn type_name(&self) -> &str {
self.base.type_name()
}
fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
self.base.parent()
}
fn connection(&self) -> Arc<dyn crate::server::connection::ConnectionLike> {
self.base.connection()
}
fn initializer(&self) -> &Value {
self.base.initializer()
}
fn channel(&self) -> &crate::server::channel::Channel {
self.base.channel()
}
fn dispose(&self, reason: crate::server::channel_owner::DisposeReason) {
self.base.dispose(reason)
}
fn adopt(&self, child: Arc<dyn ChannelOwner>) {
self.base.adopt(child)
}
fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
self.base.add_child(guid, child)
}
fn remove_child(&self, guid: &str) {
self.base.remove_child(guid)
}
fn on_event(&self, _method: &str, _params: Value) {
// ElementHandle events will be handled in future phases if needed
}
fn was_collected(&self) -> bool {
self.base.was_collected()
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl std::fmt::Debug for ElementHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ElementHandle")
.field("guid", &self.guid())
.finish()
}
}