thirtyfour/web_element.rs
1use serde::ser::{Serialize, Serializer};
2use serde_json::Value;
3use std::fmt;
4use std::path::Path;
5use std::sync::Arc;
6
7use crate::common::command::Command;
8use crate::error::{WebDriverError, WebDriverErrorInner};
9use crate::extensions::query::ElementWaitable;
10use crate::js::SIMULATE_DRAG_AND_DROP;
11use crate::session::handle::SessionHandle;
12use crate::support::base64_decode;
13use crate::{By, ElementRef, common::types::ElementRect, error::WebDriverResult};
14use crate::{ElementId, TypingData};
15use crate::{IntoArcStr, support};
16
17/// The WebElement struct encapsulates a single element on a page.
18///
19/// WebElement structs are generally not constructed manually, but rather
20/// they are returned from a 'find_element()' operation using a WebDriver.
21///
22/// # Example:
23/// ```no_run
24/// # use thirtyfour::prelude::*;
25/// # use thirtyfour::support::block_on;
26/// #
27/// # fn main() -> WebDriverResult<()> {
28/// # block_on(async {
29/// # let caps = DesiredCapabilities::chrome();
30/// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
31/// let elem = driver.find(By::Id("my-element-id")).await?;
32/// # driver.quit().await?;
33/// # Ok(())
34/// # })
35/// # }
36/// ```
37///
38/// You can also search for a child element of another element as follows:
39/// ```no_run
40/// # use thirtyfour::prelude::*;
41/// # use thirtyfour::support::block_on;
42/// #
43/// # fn main() -> WebDriverResult<()> {
44/// # block_on(async {
45/// # let caps = DesiredCapabilities::chrome();
46/// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
47/// let elem = driver.find(By::Id("my-element-id")).await?;
48/// let child_elem = elem.find(By::Tag("button")).await?;
49/// # driver.quit().await?;
50/// # Ok(())
51/// # })
52/// # }
53/// ```
54///
55/// Elements can be clicked using the `click()` method, and you can send
56/// input to an element using the `send_keys()` method.
57///
58#[derive(Clone)]
59pub struct WebElement {
60 pub(crate) element_id: ElementId,
61 pub(crate) handle: Arc<SessionHandle>,
62}
63
64impl fmt::Debug for WebElement {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.debug_struct("WebElement").field("element", &self.element_id).finish()
67 }
68}
69
70impl PartialEq for WebElement {
71 fn eq(&self, other: &Self) -> bool {
72 self.element_id() == other.element_id()
73 }
74}
75
76impl Eq for WebElement {}
77
78impl WebElement {
79 /// Create a new WebElement struct.
80 ///
81 /// Typically you would not call this directly. WebElement structs are
82 /// usually constructed by calling one of the find_element*() methods
83 /// either on WebDriver or another WebElement.
84 pub(crate) fn new(element_id: ElementId, handle: Arc<SessionHandle>) -> Self {
85 Self {
86 element_id,
87 handle,
88 }
89 }
90
91 /// Construct a `WebElement` from a JSON response and a session handle.
92 ///
93 /// The `value` argument should be a JSON object containing the property
94 /// `element-6066-11e4-a52e-4f735466cecf` whose value is the element id
95 /// assigned by the WebDriver.
96 ///
97 /// You can get the session handle from any existing `WebDriver` or
98 /// `WebElement` that is using this session, e.g. `driver.handle()`.
99 ///
100 /// NOTE: if you simply want to convert a script's return value to a
101 /// `WebElement`, use [`ScriptRet::element`] instead.
102 ///
103 /// [`ScriptRet::element`]: crate::session::scriptret::ScriptRet::element
104 pub fn from_json(value: Value, handle: Arc<SessionHandle>) -> WebDriverResult<Self> {
105 let element_ref: ElementRef = serde_json::from_value(value)?;
106 Ok(Self {
107 element_id: ElementId::from(element_ref.id()),
108 handle,
109 })
110 }
111
112 /// Serialize this `WebElement` to JSON.
113 ///
114 /// This is useful for supplying an element as an argument to a script.
115 ///
116 /// See the documentation for [`SessionHandle::execute`] for more details.
117 pub fn to_json(&self) -> WebDriverResult<Value> {
118 Ok(serde_json::to_value(ElementRef::Element {
119 id: self.element_id.to_string(),
120 })?)
121 }
122
123 /// Get the internal element id for this element.
124 ///
125 /// NOTE: If you want the `id` property of an element,
126 /// use [`WebElement::id`] instead.
127 pub fn element_id(&self) -> ElementId {
128 self.element_id.clone()
129 }
130
131 /// Returns a reference to the underlying [`SessionHandle`].
132 /// Useful for extension code that needs to clone the handle.
133 pub fn handle(&self) -> &Arc<SessionHandle> {
134 &self.handle
135 }
136
137 /// Resolve this WebElement to a CDP `RemoteObjectId` so it can be passed
138 /// to `Runtime.callFunctionOn`, `DOM.requestNode`, etc.
139 ///
140 /// Bridge: stashes the element on a unique `window.__thirtyfour_cdp_*`
141 /// property via `executeScript`, then `Runtime.evaluate`s a one-shot
142 /// IIFE that reads-and-deletes the property, returning the element as
143 /// a `RemoteObject` handle. Requires a Chromium-based session.
144 #[cfg(feature = "cdp")]
145 pub async fn cdp_remote_object_id(&self) -> WebDriverResult<crate::cdp::RemoteObjectId> {
146 use std::sync::atomic::{AtomicU64, Ordering};
147 static SEQ: AtomicU64 = AtomicU64::new(0);
148 let key = format!(
149 "__thirtyfour_cdp_{}_{}",
150 std::process::id(),
151 SEQ.fetch_add(1, Ordering::Relaxed)
152 );
153 let stash = format!("window['{key}'] = arguments[0];");
154 self.handle.execute(stash, vec![self.to_json()?]).await?;
155 let take =
156 format!("(function(){{var e=window['{key}'];delete window['{key}'];return e;}})()");
157 let cdp = crate::cdp::Cdp::new(self.handle.clone());
158 let result = cdp.send(crate::cdp::domains::runtime::Evaluate::new(take)).await?;
159 result.result.object_id.ok_or_else(|| {
160 WebDriverError::from_inner(WebDriverErrorInner::NotFound(
161 "RemoteObjectId".to_string(),
162 "CDP Runtime.evaluate did not return an object handle".to_string(),
163 ))
164 })
165 }
166
167 /// Resolve this WebElement to a CDP `BackendNodeId`.
168 ///
169 /// Stable across `DOM` agent reattachment, so this is the right id to
170 /// stash if you need to refer back to the element from later CDP calls.
171 /// Requires a Chromium-based session.
172 #[cfg(feature = "cdp")]
173 pub async fn cdp_backend_node_id(&self) -> WebDriverResult<crate::cdp::BackendNodeId> {
174 let object_id = self.cdp_remote_object_id().await?;
175 let cdp = crate::cdp::Cdp::new(self.handle.clone());
176 let described = cdp
177 .send(crate::cdp::domains::dom::DescribeNode {
178 object_id: Some(object_id),
179 ..Default::default()
180 })
181 .await?;
182 Ok(described.node.backend_node_id)
183 }
184
185 /// Get the bounding rectangle for this WebElement.
186 ///
187 /// # Example:
188 /// ```no_run
189 /// # use thirtyfour::prelude::*;
190 /// # use thirtyfour::support::block_on;
191 /// #
192 /// # fn main() -> WebDriverResult<()> {
193 /// # block_on(async {
194 /// # let caps = DesiredCapabilities::chrome();
195 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
196 /// let elem = driver.find(By::Id("button1")).await?;
197 /// let r = elem.rect().await?;
198 /// # driver.quit().await?;
199 /// # Ok(())
200 /// # })
201 /// # }
202 /// ```
203 pub async fn rect(&self) -> WebDriverResult<ElementRect> {
204 let r = self.handle.cmd(Command::GetElementRect(self.element_id.clone())).await?;
205 r.value()
206 }
207
208 /// Get the tag name for this WebElement.
209 ///
210 /// # Example:
211 /// ```no_run
212 /// # use thirtyfour::prelude::*;
213 /// # use thirtyfour::support::block_on;
214 /// #
215 /// # fn main() -> WebDriverResult<()> {
216 /// # block_on(async {
217 /// # let caps = DesiredCapabilities::chrome();
218 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
219 /// let elem = driver.find(By::Id("button1")).await?;
220 /// assert_eq!(elem.tag_name().await?, "button");
221 /// # driver.quit().await?;
222 /// # Ok(())
223 /// # })
224 /// # }
225 /// ```
226 pub async fn tag_name(&self) -> WebDriverResult<String> {
227 self.handle.cmd(Command::GetElementTagName(self.element_id.clone())).await?.value()
228 }
229
230 /// Get the class name for this WebElement.
231 ///
232 /// # Example:
233 /// ```no_run
234 /// # use thirtyfour::prelude::*;
235 /// # use thirtyfour::support::block_on;
236 /// #
237 /// # fn main() -> WebDriverResult<()> {
238 /// # block_on(async {
239 /// # let caps = DesiredCapabilities::chrome();
240 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
241 /// let elem = driver.find(By::Id("button1")).await?;
242 /// let class_name: Option<String> = elem.class_name().await?;
243 /// # driver.quit().await?;
244 /// # Ok(())
245 /// # })
246 /// # }
247 /// ```
248 pub async fn class_name(&self) -> WebDriverResult<Option<String>> {
249 self.attr("class").await
250 }
251
252 /// Get the id for this WebElement.
253 ///
254 /// # Example:
255 /// ```no_run
256 /// # use thirtyfour::prelude::*;
257 /// # use thirtyfour::support::block_on;
258 /// #
259 /// # fn main() -> WebDriverResult<()> {
260 /// # block_on(async {
261 /// # let caps = DesiredCapabilities::chrome();
262 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
263 /// let elem = driver.find(By::Id("button1")).await?;
264 /// let id: Option<String> = elem.id().await?;
265 /// # driver.quit().await?;
266 /// # Ok(())
267 /// # })
268 /// # }
269 /// ```
270 pub async fn id(&self) -> WebDriverResult<Option<String>> {
271 self.attr("id").await
272 }
273
274 /// Get the text contents for this WebElement.
275 ///
276 /// # Example:
277 /// ```no_run
278 /// # use thirtyfour::prelude::*;
279 /// # use thirtyfour::support::block_on;
280 /// #
281 /// # fn main() -> WebDriverResult<()> {
282 /// # block_on(async {
283 /// # let caps = DesiredCapabilities::chrome();
284 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
285 /// let elem = driver.find(By::Id("button1")).await?;
286 /// let text = elem.text().await?;
287 /// assert_eq!(text, "Click Me");
288 /// # driver.quit().await?;
289 /// # Ok(())
290 /// # })
291 /// # }
292 /// ```
293 pub async fn text(&self) -> WebDriverResult<String> {
294 self.handle.cmd(Command::GetElementText(self.element_id.clone())).await?.value()
295 }
296
297 /// Convenience method for getting the (optional) value property of this element.
298 pub async fn value(&self) -> WebDriverResult<Option<String>> {
299 self.prop("value").await
300 }
301
302 /// Click the WebElement.
303 ///
304 /// # Example:
305 /// ```no_run
306 /// # use thirtyfour::prelude::*;
307 /// # use thirtyfour::support::block_on;
308 /// #
309 /// # fn main() -> WebDriverResult<()> {
310 /// # block_on(async {
311 /// # let caps = DesiredCapabilities::chrome();
312 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
313 /// let elem = driver.find(By::Id("button1")).await?;
314 /// elem.click().await?;
315 /// # driver.quit().await?;
316 /// # Ok(())
317 /// # })
318 /// # }
319 /// ```
320 pub async fn click(&self) -> WebDriverResult<()> {
321 self.handle.cmd(Command::ElementClick(self.element_id.clone())).await?;
322 Ok(())
323 }
324
325 /// Wait for the WebElement to be displayed and enabled, then click it.
326 ///
327 /// This is equivalent to `self.wait_until().clickable().await?; self.click().await`. Here,
328 /// clickable means displayed and enabled; it is not a complete interactability guarantee.
329 /// This method acts on this already-resolved element, clicks once, and does not re-resolve a
330 /// stale element, retry a failed click, or wait for an outcome. The click can still fail if,
331 /// for example, another element intercepts it after the readiness check.
332 ///
333 /// # Example:
334 /// ```no_run
335 /// # use thirtyfour::prelude::*;
336 /// # use thirtyfour::support::block_on;
337 /// #
338 /// # fn main() -> WebDriverResult<()> {
339 /// # block_on(async {
340 /// # let caps = DesiredCapabilities::chrome();
341 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
342 /// let elem = driver.find(By::Id("button1")).await?;
343 /// elem.click_when_ready().await?;
344 /// # driver.quit().await?;
345 /// # Ok(())
346 /// # })
347 /// # }
348 /// ```
349 pub async fn click_when_ready(&self) -> WebDriverResult<()> {
350 self.wait_until().clickable().await?;
351 self.click().await
352 }
353
354 /// Clear the WebElement contents.
355 ///
356 /// # Example:
357 /// ```no_run
358 /// # use thirtyfour::prelude::*;
359 /// # use thirtyfour::support::block_on;
360 /// #
361 /// # fn main() -> WebDriverResult<()> {
362 /// # block_on(async {
363 /// # let caps = DesiredCapabilities::chrome();
364 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
365 /// let elem = driver.find(By::Css("input[type='text']")).await?;
366 /// elem.clear().await?;
367 /// # driver.quit().await?;
368 /// # Ok(())
369 /// # })
370 /// # }
371 /// ```
372 pub async fn clear(&self) -> WebDriverResult<()> {
373 self.handle.cmd(Command::ElementClear(self.element_id.clone())).await?;
374 Ok(())
375 }
376
377 /// Get the specified property.
378 ///
379 /// # Example:
380 /// ```no_run
381 /// # use thirtyfour::prelude::*;
382 /// # use thirtyfour::support::block_on;
383 /// #
384 /// # fn main() -> WebDriverResult<()> {
385 /// # block_on(async {
386 /// # let caps = DesiredCapabilities::chrome();
387 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
388 /// let elem = driver.find(By::Css("input[type='checkbox']")).await?;
389 /// let property_value: Option<String> = elem.prop("checked").await?;
390 /// assert_eq!(property_value.unwrap(), "true");
391 ///
392 /// // If a property is not found, None is returned.
393 /// assert_eq!(elem.prop("invalid-property").await?, None);
394 /// # driver.quit().await?;
395 /// # Ok(())
396 /// # })
397 /// # }
398 /// ```
399 pub async fn prop(&self, name: impl IntoArcStr) -> WebDriverResult<Option<String>> {
400 let resp = self
401 .handle
402 .cmd(Command::GetElementProperty(self.element_id.clone(), name.into()))
403 .await?;
404 match resp.value()? {
405 Value::String(v) => Ok(Some(v)),
406 Value::Bool(b) => Ok(Some(b.to_string())),
407 Value::Number(number) => Ok(Some(number.to_string())),
408 Value::Null => Ok(None),
409 v => Err(WebDriverError::Json(format!("Unexpected value for property: {:?}", v))),
410 }
411 }
412
413 /// Get the specified attribute.
414 ///
415 /// # Example:
416 /// ```no_run
417 /// # use thirtyfour::prelude::*;
418 /// # use thirtyfour::support::block_on;
419 /// #
420 /// # fn main() -> WebDriverResult<()> {
421 /// # block_on(async {
422 /// # let caps = DesiredCapabilities::chrome();
423 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
424 /// let elem = driver.find(By::Name("input2")).await?;
425 /// let attribute: Option<String> = elem.attr("name").await?;
426 /// assert_eq!(attribute.unwrap(), "input2");
427 ///
428 /// // If the attribute does not exist, None is returned.
429 /// assert_eq!(elem.attr("invalid-attribute").await?, None);
430 /// # driver.quit().await?;
431 /// # Ok(())
432 /// # })
433 /// # }
434 /// ```
435 pub async fn attr(&self, name: impl IntoArcStr) -> WebDriverResult<Option<String>> {
436 self.handle
437 .cmd(Command::GetElementAttribute(self.element_id.clone(), name.into()))
438 .await?
439 .value()
440 }
441
442 /// Get the specified CSS property.
443 ///
444 /// # Example:
445 /// ```no_run
446 /// # use thirtyfour::prelude::*;
447 /// # use thirtyfour::support::block_on;
448 /// #
449 /// # fn main() -> WebDriverResult<()> {
450 /// # block_on(async {
451 /// # let caps = DesiredCapabilities::chrome();
452 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
453 /// let elem = driver.find(By::Id("my-element-id")).await?;
454 /// let css_color = elem.css_value("color").await?;
455 /// assert_eq!(css_color, "rgba(0, 0, 0, 1)");
456 ///
457 /// // If an invalid CSS property is specified, a blank string is returned.
458 /// assert_eq!(elem.css_value("invalid-css-property").await?, "");
459 /// # driver.quit().await?;
460 /// # Ok(())
461 /// # })
462 /// # }
463 /// ```
464 pub async fn css_value(&self, name: impl IntoArcStr) -> WebDriverResult<String> {
465 self.handle
466 .cmd(Command::GetElementCssValue(self.element_id.clone(), name.into()))
467 .await?
468 .value()
469 }
470
471 /// Return true if the WebElement is currently selected, otherwise false.
472 pub async fn is_selected(&self) -> WebDriverResult<bool> {
473 self.handle.cmd(Command::IsElementSelected(self.element_id.clone())).await?.value()
474 }
475
476 /// Return true if the WebElement is currently displayed, otherwise false.
477 ///
478 /// # Example
479 /// ```no_run
480 /// # use thirtyfour::prelude::*;
481 /// # use thirtyfour::support::block_on;
482 /// #
483 /// # fn main() -> WebDriverResult<()> {
484 /// # block_on(async {
485 /// # let caps = DesiredCapabilities::chrome();
486 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
487 /// let elem = driver.find(By::Id("button1")).await?;
488 /// assert!(elem.is_displayed().await?);
489 /// # driver.quit().await?;
490 /// # Ok(())
491 /// # })
492 /// # }
493 /// ```
494 pub async fn is_displayed(&self) -> WebDriverResult<bool> {
495 self.handle.cmd(Command::IsElementDisplayed(self.element_id.clone())).await?.value()
496 }
497
498 /// Return true if the WebElement is currently enabled, otherwise false.
499 ///
500 /// # Example
501 /// ```no_run
502 /// # use thirtyfour::prelude::*;
503 /// # use thirtyfour::support::block_on;
504 /// #
505 /// # fn main() -> WebDriverResult<()> {
506 /// # block_on(async {
507 /// # let caps = DesiredCapabilities::chrome();
508 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
509 /// let elem = driver.find(By::Id("button1")).await?;
510 /// assert!(elem.is_enabled().await?);
511 /// # driver.quit().await?;
512 /// # Ok(())
513 /// # })
514 /// # }
515 /// ```
516 pub async fn is_enabled(&self) -> WebDriverResult<bool> {
517 self.handle.cmd(Command::IsElementEnabled(self.element_id.clone())).await?.value()
518 }
519
520 /// Return true if the WebElement is currently clickable (visible and enabled),
521 /// otherwise false.
522 ///
523 /// # Example
524 /// ```no_run
525 /// # use thirtyfour::prelude::*;
526 /// # use thirtyfour::support::block_on;
527 /// #
528 /// # fn main() -> WebDriverResult<()> {
529 /// # block_on(async {
530 /// # let caps = DesiredCapabilities::chrome();
531 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
532 /// let elem = driver.find(By::Id("button1")).await?;
533 /// assert!(elem.is_clickable().await?);
534 /// # driver.quit().await?;
535 /// # Ok(())
536 /// # })
537 /// # }
538 /// ```
539 pub async fn is_clickable(&self) -> WebDriverResult<bool> {
540 Ok(self.is_displayed().await? && self.is_enabled().await?)
541 }
542
543 /// Return true if the WebElement is currently (still) present
544 /// and not stale.
545 ///
546 /// NOTE: This method simply queries the tag name to
547 /// determine whether the element is still present.
548 ///
549 /// IMPORTANT:
550 /// If an element is re-rendered, it may be considered stale even
551 /// though to the user it looks like it is still there.
552 ///
553 /// The recommended way to check for the presence of an element is
554 /// to simply search for the element again.
555 ///
556 /// # Example
557 /// ```no_run
558 /// # use thirtyfour::prelude::*;
559 /// # use thirtyfour::support::block_on;
560 /// #
561 /// # fn main() -> WebDriverResult<()> {
562 /// # block_on(async {
563 /// # let caps = DesiredCapabilities::chrome();
564 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
565 /// let elem = driver.find(By::Id("button1")).await?;
566 /// assert!(elem.is_present().await?);
567 /// # driver.quit().await?;
568 /// # Ok(())
569 /// # })
570 /// # }
571 /// ```
572 pub async fn is_present(&self) -> WebDriverResult<bool> {
573 let present = match self.tag_name().await {
574 Ok(..) => true,
575 Err(e) if matches!(*e, WebDriverErrorInner::StaleElementReference(..)) => false,
576 Err(e) => return Err(e),
577 };
578 Ok(present)
579 }
580
581 /// Search for a child element of this WebElement using the specified selector.
582 ///
583 /// **NOTE**: For more powerful element queries including polling and filters, see the
584 /// [`WebElement::query`] method instead.
585 ///
586 /// [`WebElement::query`]: crate::extensions::query::ElementQueryable::query
587 ///
588 /// # Example:
589 /// ```no_run
590 /// # use thirtyfour::prelude::*;
591 /// # use thirtyfour::support::block_on;
592 /// #
593 /// # fn main() -> WebDriverResult<()> {
594 /// # block_on(async {
595 /// # let caps = DesiredCapabilities::chrome();
596 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
597 /// let elem = driver.find(By::Id("my-element-id")).await?;
598 /// let child_elem = elem.find(By::Tag("button")).await?;
599 /// # driver.quit().await?;
600 /// # Ok(())
601 /// # })
602 /// # }
603 /// ```
604 pub async fn find(&self, by: By) -> WebDriverResult<WebElement> {
605 let r = self
606 .handle
607 .cmd(Command::FindElementFromElement(self.element_id.clone(), by.into()))
608 .await?;
609 r.element(self.handle.clone())
610 }
611
612 /// Search for all child elements of this WebElement that match the specified selector.
613 ///
614 /// **NOTE**: For more powerful element queries including polling and filters, see the
615 /// [`WebElement::query`] method instead.
616 ///
617 /// [`WebElement::query`]: crate::extensions::query::ElementQueryable::query
618 ///
619 /// # Example:
620 /// ```no_run
621 /// # use thirtyfour::prelude::*;
622 /// # use thirtyfour::support::block_on;
623 /// #
624 /// # fn main() -> WebDriverResult<()> {
625 /// # block_on(async {
626 /// # let caps = DesiredCapabilities::chrome();
627 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
628 /// let elem = driver.find(By::Id("my-element-id")).await?;
629 /// let child_elems = elem.find_all(By::Tag("button")).await?;
630 /// for child_elem in child_elems {
631 /// assert_eq!(child_elem.tag_name().await?, "button");
632 /// }
633 /// # driver.quit().await?;
634 /// # Ok(())
635 /// # })
636 /// # }
637 /// ```
638 pub async fn find_all(&self, by: By) -> WebDriverResult<Vec<WebElement>> {
639 let r = self
640 .handle
641 .cmd(Command::FindElementsFromElement(self.element_id.clone(), by.into()))
642 .await?;
643 r.elements(self.handle.clone())
644 }
645
646 /// Send the specified input.
647 ///
648 /// # Example:
649 /// ```no_run
650 /// # use thirtyfour::prelude::*;
651 /// # use thirtyfour::support::block_on;
652 /// #
653 /// # fn main() -> WebDriverResult<()> {
654 /// # block_on(async {
655 /// # let caps = DesiredCapabilities::chrome();
656 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
657 /// let elem = driver.find(By::Name("input1")).await?;
658 /// elem.send_keys("thirtyfour").await?;
659 /// # driver.quit().await?;
660 /// # Ok(())
661 /// # })
662 /// # }
663 /// ```
664 ///
665 /// You can also send special key combinations like this:
666 /// ```no_run
667 /// # use thirtyfour::prelude::*;
668 /// # use thirtyfour::support::block_on;
669 /// #
670 /// # fn main() -> WebDriverResult<()> {
671 /// block_on(async {
672 /// # let caps = DesiredCapabilities::chrome();
673 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
674 /// let elem = driver.find(By::Name("input1")).await?;
675 /// elem.send_keys("selenium").await?;
676 /// elem.send_keys(Key::Control + "a").await?;
677 /// elem.send_keys("thirtyfour" + Key::Enter).await?;
678 /// # driver.quit().await?;
679 /// # Ok(())
680 /// # })
681 /// # }
682 /// ```
683 pub async fn send_keys(&self, key: impl Into<TypingData>) -> WebDriverResult<()> {
684 self.handle.cmd(Command::ElementSendKeys(self.element_id.clone(), key.into())).await?;
685 Ok(())
686 }
687
688 /// Take a screenshot of this WebElement and return it as PNG, base64 encoded.
689 pub async fn screenshot_as_png_base64(&self) -> WebDriverResult<String> {
690 self.handle.cmd(Command::TakeElementScreenshot(self.element_id.clone())).await?.value()
691 }
692
693 /// Take a screenshot of this WebElement and return it as PNG bytes.
694 pub async fn screenshot_as_png(&self) -> WebDriverResult<Vec<u8>> {
695 base64_decode(&self.screenshot_as_png_base64().await?)
696 }
697
698 /// Take a screenshot of this WebElement and write it to the specified filename.
699 pub async fn screenshot(&self, path: &Path) -> WebDriverResult<()> {
700 let png = self.screenshot_as_png().await?;
701 support::write_file(path, png).await?;
702 Ok(())
703 }
704
705 /// Focus this WebElement using JavaScript.
706 ///
707 /// # Example:
708 /// ```no_run
709 /// # use thirtyfour::prelude::*;
710 /// # use thirtyfour::support::block_on;
711 /// #
712 /// # fn main() -> WebDriverResult<()> {
713 /// # block_on(async {
714 /// # let caps = DesiredCapabilities::chrome();
715 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
716 /// let elem = driver.find(By::Name("input1")).await?;
717 /// elem.focus().await?;
718 /// # driver.quit().await?;
719 /// # Ok(())
720 /// # })
721 /// # }
722 /// ```
723 pub async fn focus(&self) -> WebDriverResult<()> {
724 self.handle.execute(r#"arguments[0].focus();"#, vec![self.to_json()?]).await?;
725 Ok(())
726 }
727
728 /// Scroll this element into view using JavaScript.
729 ///
730 /// # Example:
731 /// ```no_run
732 /// # use thirtyfour::prelude::*;
733 /// # use thirtyfour::support::block_on;
734 /// #
735 /// # fn main() -> WebDriverResult<()> {
736 /// # block_on(async {
737 /// # let caps = DesiredCapabilities::chrome();
738 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
739 /// let elem = driver.find(By::Id("button1")).await?;
740 /// elem.scroll_into_view().await?;
741 /// # driver.quit().await?;
742 /// # Ok(())
743 /// # })
744 /// # }
745 /// ```
746 pub async fn scroll_into_view(&self) -> WebDriverResult<()> {
747 self.handle
748 .execute(
749 r#"arguments[0].scrollIntoView({block: "center", inline: "center"});"#,
750 vec![self.to_json()?],
751 )
752 .await?;
753 Ok(())
754 }
755
756 /// Get the innerHtml property of this element.
757 ///
758 /// # Example:
759 /// ```no_run
760 /// # use thirtyfour::prelude::*;
761 /// # use thirtyfour::support::block_on;
762 /// #
763 /// # fn main() -> WebDriverResult<()> {
764 /// # block_on(async {
765 /// # let caps = DesiredCapabilities::chrome();
766 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
767 /// let elem = driver.find(By::Id("my-element-id")).await?;
768 /// let html = elem.inner_html().await?;
769 /// # driver.quit().await?;
770 /// # Ok(())
771 /// # })
772 /// # }
773 /// ```
774 pub async fn inner_html(&self) -> WebDriverResult<String> {
775 self.prop("innerHTML").await.map(|x| x.unwrap_or_default())
776 }
777
778 /// Get the outerHtml property of this element.
779 ///
780 /// # Example:
781 /// ```no_run
782 /// # use thirtyfour::prelude::*;
783 /// # use thirtyfour::support::block_on;
784 /// #
785 /// # fn main() -> WebDriverResult<()> {
786 /// # block_on(async {
787 /// # let caps = DesiredCapabilities::chrome();
788 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
789 /// let elem = driver.find(By::Id("my-element-id")).await?;
790 /// let html = elem.outer_html().await?;
791 /// # driver.quit().await?;
792 /// # Ok(())
793 /// # })
794 /// # }
795 /// ```
796 pub async fn outer_html(&self) -> WebDriverResult<String> {
797 self.prop("outerHTML").await.map(|x| x.unwrap_or_default())
798 }
799
800 /// Get the shadowRoot property of the current element.
801 ///
802 /// Call this method on the element containing the `#shadowRoot` node.
803 /// You can then use the returned `WebElement` to query elements within the shadowRoot node.
804 pub async fn get_shadow_root(&self) -> WebDriverResult<WebElement> {
805 let ret =
806 self.handle.execute("return arguments[0].shadowRoot", vec![self.to_json()?]).await?;
807 ret.element()
808 }
809
810 /// Switch to the specified iframe element.
811 ///
812 /// # Example:
813 /// ```no_run
814 /// # use thirtyfour::prelude::*;
815 /// # use thirtyfour::support::block_on;
816 /// #
817 /// # fn main() -> WebDriverResult<()> {
818 /// # block_on(async {
819 /// # let caps = DesiredCapabilities::chrome();
820 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
821 /// let elem_iframe = driver.find(By::Id("iframeid1")).await?;
822 /// elem_iframe.enter_frame().await?;
823 /// // We can now search for elements within the iframe.
824 /// let elem = driver.find(By::Id("button1")).await?;
825 /// elem.click().await?;
826 /// # driver.quit().await?;
827 /// # Ok(())
828 /// # })
829 /// # }
830 /// ```
831 pub async fn enter_frame(self) -> WebDriverResult<()> {
832 self.handle.cmd(Command::SwitchToFrameElement(self.element_id.clone())).await?;
833 Ok(())
834 }
835
836 /// Drag the element to a target element using JavaScript.
837 ///
838 /// # Example
839 /// ```no_run
840 /// # use thirtyfour::prelude::*;
841 /// # use thirtyfour::support::block_on;
842 /// #
843 /// # fn main() -> WebDriverResult<()> {
844 /// # block_on(async {
845 /// # let caps = DesiredCapabilities::chrome();
846 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
847 /// let elem = driver.find(By::Id("draggable")).await?;
848 /// let target = driver.find(By::Id("target")).await?;
849 /// elem.js_drag_to(&target).await?;
850 /// # driver.quit().await?;
851 /// # Ok(())
852 /// # })
853 /// # }
854 /// ```
855 pub async fn js_drag_to(&self, target: &Self) -> WebDriverResult<()> {
856 self.handle
857 .execute(SIMULATE_DRAG_AND_DROP, vec![self.to_json()?, target.to_json()?])
858 .await?;
859 Ok(())
860 }
861
862 /// Get the parent of the WebElement.
863 ///
864 /// # Example
865 /// ```no_run
866 /// # use thirtyfour::prelude::*;
867 /// # use thirtyfour::support::block_on;
868 /// #
869 /// # fn main() -> WebDriverResult<()> {
870 /// # block_on(async {
871 /// # let caps = DesiredCapabilities::chrome();
872 /// # let driver = WebDriver::new("http://localhost:4444", caps).await?;
873 /// let elem = driver.find(By::Id("child")).await?;
874 /// let parent = elem.parent().await?;
875 /// # driver.quit().await?;
876 /// # Ok(())
877 /// # })
878 /// # }
879 /// ```
880 pub async fn parent(&self) -> WebDriverResult<Self> {
881 self.find(By::XPath("./..")).await
882 }
883}
884
885impl fmt::Display for WebElement {
886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887 write!(f, "{:?}", self.element_id)
888 }
889}
890
891impl Serialize for WebElement {
892 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
893 where
894 S: Serializer,
895 {
896 self.element_id.serialize(serializer)
897 }
898}