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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Frame API -- mirrors Playwright's Frame interface.
//!
//! A Frame represents an execution context within a Page.
//! The main frame is the top-level page frame. Child frames
//! correspond to `<iframe>` elements.
//!
//! Frame has the same evaluation and locator methods as Page,
//! but scoped to its specific frame context.
use std::sync::Arc;
use crate::error::Result;
use crate::locator::Locator;
use crate::options::{RoleOptions, StringOrRegex, TextOptions, WaitOptions};
use crate::page::Page;
/// A frame within a page. Mirrors Playwright's
/// [Frame interface](https://playwright.dev/docs/api/class-frame).
///
/// Frame instances are thin handles — the authoritative name/url/parent
/// state lives in `crate::frame_cache::FrameCache` on the owning Page.
/// Cloning a Frame is cheap (`Arc<Page>` + `Arc<str>`) and multiple
/// clones see the same live state.
#[derive(Clone)]
pub struct Frame {
/// The page this frame belongs to (Arc for cheap cloning in locator chains).
page: Arc<Page>,
/// Frame ID (from CDP or backend). `Arc<str>` so locator chains are cheap.
pub(crate) id: Arc<str>,
}
impl Frame {
/// Create a frame handle pointing at an id present in the page's
/// frame cache. The cache is the source of truth for name/url/parent.
pub(crate) fn new(page: Arc<Page>, id: Arc<str>) -> Self {
Self { page, id }
}
/// Backend-issued frame identifier. Sync — the underlying `Arc<str>`
/// is set at construction. Used by the network module to match
/// `Request.frame()` lookups against the page's frame cache.
#[must_use]
pub fn frame_id(&self) -> &str {
&self.id
}
/// Frame name (from the `name` attribute of the iframe element).
/// Playwright: [`frame.name()`](https://playwright.dev/docs/api/class-frame#frame-name)
/// -- `name(): string` sync, reads cached state.
#[must_use]
pub fn name(&self) -> String {
self
.page
.with_frame_cache(|c| c.record(&self.id).map(|r| r.info.name.clone()).unwrap_or_default())
}
/// Frame URL.
/// Playwright: [`frame.url()`](https://playwright.dev/docs/api/class-frame#frame-url)
/// -- `url(): string` sync.
#[must_use]
pub fn url(&self) -> String {
self
.page
.with_frame_cache(|c| c.record(&self.id).map(|r| r.info.url.clone()).unwrap_or_default())
}
/// Whether this is the main (top-level) frame. Mirrors Playwright's
/// equivalent of `frame.parentFrame() === null`.
#[must_use]
pub fn is_main_frame(&self) -> bool {
self
.page
.with_frame_cache(|c| c.main_frame_id().as_deref() == Some(&*self.id))
}
/// Parent frame. Returns `None` for the main frame. Sync — reads from
/// the page's frame cache (Playwright:
/// [`frame.parentFrame()`](https://playwright.dev/docs/api/class-frame#frame-parent-frame)).
#[must_use]
pub fn parent_frame(&self) -> Option<Frame> {
let pid = self.page.with_frame_cache(|c| c.parent_id(&self.id))?;
Some(Frame::new(Arc::clone(&self.page), pid))
}
/// Child frames. Sync — reads from the page's frame cache.
/// Playwright: [`frame.childFrames()`](https://playwright.dev/docs/api/class-frame#frame-child-frames).
#[must_use]
pub fn child_frames(&self) -> Vec<Frame> {
let ids = self.page.with_frame_cache(|c| c.child_ids(&self.id));
ids
.into_iter()
.map(|id| Frame::new(Arc::clone(&self.page), id))
.collect()
}
// ── Evaluation (frame-scoped) ────────────────────────────────────────
/// Playwright: `frame.evaluate(pageFunction, arg?): Promise<R>`
/// (`/tmp/playwright/packages/playwright-core/src/client/frame.ts:196`).
///
/// Runs `fn_source` in this frame's execution context with `arg`
/// serialised through the isomorphic wire protocol. Main-frame calls
/// pass `frame_id = None`; child-frame calls thread `self.id()` so
/// the utility script resolves the target frame's context.
///
/// # Errors
///
/// Returns a [`crate::error::FerriError`] on page-side exception or
/// protocol failure.
pub async fn evaluate(
&self,
fn_source: &str,
arg: crate::protocol::SerializedArgument,
is_function: Option<bool>,
) -> Result<crate::protocol::SerializedValue> {
let frame_id = if self.is_main_frame() { None } else { Some(&*self.id) };
let empty = matches!(
arg.value,
crate::protocol::SerializedValue::Special(crate::protocol::SpecialValue::Undefined)
) && arg.handles.is_empty();
let args_slice: &[crate::protocol::SerializedValue] = if empty { &[] } else { std::slice::from_ref(&arg.value) };
let result = self
.page
.inner
.call_utility_evaluate(fn_source, args_slice, &arg.handles, frame_id, is_function, true)
.await?;
match result {
crate::js_handle::EvaluateResult::Value(v) => Ok(v),
crate::js_handle::EvaluateResult::Handle(..) => Err(crate::error::FerriError::Evaluation(
"Frame::evaluate: backend returned handle but returnByValue=true was requested".into(),
)),
}
}
/// Playwright: `frame.evaluateHandle(pageFunction, arg?): Promise<JSHandle>`
/// (`/tmp/playwright/packages/playwright-core/src/client/frame.ts:190`).
///
/// Same wire path as [`Self::evaluate`] but retains the result on
/// the page and hands back a fresh [`crate::js_handle::JSHandle`].
///
/// # Errors
///
/// See [`Self::evaluate`].
pub async fn evaluate_handle(
&self,
fn_source: &str,
arg: crate::protocol::SerializedArgument,
is_function: Option<bool>,
) -> Result<crate::js_handle::JSHandle> {
let frame_id = if self.is_main_frame() { None } else { Some(&*self.id) };
let empty = matches!(
arg.value,
crate::protocol::SerializedValue::Special(crate::protocol::SpecialValue::Undefined)
) && arg.handles.is_empty();
let args_slice: &[crate::protocol::SerializedValue] = if empty { &[] } else { std::slice::from_ref(&arg.value) };
let result = self
.page
.inner
.call_utility_evaluate(fn_source, args_slice, &arg.handles, frame_id, is_function, false)
.await?;
match result {
crate::js_handle::EvaluateResult::Handle(backing, is_node) => Ok(crate::js_handle::JSHandle::from_backing(
Arc::clone(&self.page),
backing,
is_node,
)),
crate::js_handle::EvaluateResult::Value(_) => Err(crate::error::FerriError::Evaluation(
"Frame::evaluate_handle: backend returned value but returnByValue=false was requested".into(),
)),
}
}
/// Backend-level expression evaluation used by the frame's internal
/// plumbing — dispatches to the right backend method (`evaluate` vs
/// `evaluate_in_frame`) depending on whether this is the main frame.
/// Not part of the public Playwright API; public callers use
/// [`Self::evaluate`] with a function literal.
async fn backend_eval_expr(&self, expression: &str) -> Result<Option<serde_json::Value>> {
if self.is_main_frame() {
self.page.inner.evaluate(expression).await
} else {
self.page.inner.evaluate_in_frame(expression, &self.id).await
}
}
// ── Locators (frame-scoped) ──────────────────────────────────────────
/// Create a locator scoped to this frame.
///
/// Playwright: `frame.locator(selector, options?: LocatorOptions): Locator`
/// (`/tmp/playwright/packages/playwright-core/src/client/frame.ts:324`).
/// Frame-level `.locator` only accepts a selector string and honors
/// the full `LocatorOptions` bag (including `visible`).
#[must_use]
pub fn locator(&self, selector: &str, options: Option<crate::options::FilterOptions>) -> Locator {
let base = Locator::new(self.clone(), selector.to_string());
match options {
Some(opts) => base.filter(&opts),
None => base,
}
}
#[must_use]
pub fn get_by_role(&self, role: &str, opts: &RoleOptions) -> Locator {
Locator::new(self.clone(), crate::locator::build_role_selector(role, opts))
}
/// `getByText` in this frame. Accepts `string | RegExp`.
#[must_use]
pub fn get_by_text(&self, text: &StringOrRegex, opts: &TextOptions) -> Locator {
Locator::new(
self.clone(),
crate::locator::build_text_like_selector("internal:text", text, opts),
)
}
/// `getByTestId` in this frame.
#[must_use]
pub fn get_by_test_id(&self, test_id: &StringOrRegex) -> Locator {
Locator::new(
self.clone(),
crate::locator::build_testid_selector("data-testid", test_id),
)
}
/// `getByLabel` in this frame.
#[must_use]
pub fn get_by_label(&self, text: &StringOrRegex, opts: &TextOptions) -> Locator {
Locator::new(
self.clone(),
crate::locator::build_text_like_selector("internal:label", text, opts),
)
}
/// `getByPlaceholder` in this frame.
#[must_use]
pub fn get_by_placeholder(&self, text: &StringOrRegex, opts: &TextOptions) -> Locator {
Locator::new(
self.clone(),
crate::locator::build_attr_selector("placeholder", text, opts),
)
}
/// Locate elements by `alt` attribute. Mirrors Playwright's
/// `frame.getByAltText(text, options?)`.
#[must_use]
pub fn get_by_alt_text(&self, text: &StringOrRegex, opts: &TextOptions) -> Locator {
Locator::new(self.clone(), crate::locator::build_attr_selector("alt", text, opts))
}
/// Locate elements by `title` attribute. Mirrors Playwright's
/// `frame.getByTitle(text, options?)`.
#[must_use]
pub fn get_by_title(&self, text: &StringOrRegex, opts: &TextOptions) -> Locator {
Locator::new(self.clone(), crate::locator::build_attr_selector("title", text, opts))
}
/// Create a `FrameLocator` for an `<iframe>` matching `selector`
/// inside this frame's document. Mirrors Playwright's
/// `frame.frameLocator(selector)`.
#[must_use]
pub fn frame_locator(&self, selector: &str) -> crate::locator::FrameLocator {
crate::locator::FrameLocator::for_iframe_in(self.clone(), selector.to_string())
}
// ── Content (frame-scoped) ───────────────────────────────────────────
/// Get the frame's HTML content.
///
/// # Errors
///
/// Returns an error if JS evaluation fails.
pub async fn content(&self) -> Result<String> {
let r = self.backend_eval_expr("document.documentElement.outerHTML").await?;
Ok(
r.and_then(|v| v.as_str().map(std::string::ToString::to_string))
.unwrap_or_default(),
)
}
/// Get the frame's title.
///
/// # Errors
///
/// Returns an error if JS evaluation fails.
pub async fn title(&self) -> Result<String> {
let r = self.backend_eval_expr("document.title").await?;
Ok(
r.and_then(|v| v.as_str().map(std::string::ToString::to_string))
.unwrap_or_default(),
)
}
// ── Navigation (frame-scoped) ────────────────────────────────────────
/// Navigate this frame to a URL.
///
/// # Errors
///
/// Returns an error if navigation fails.
pub async fn goto(&self, url: &str) -> Result<Option<crate::network::Response>> {
if self.is_main_frame() {
self.page.goto(url, None).await
} else {
// For child frames, set location via JS
self
.backend_eval_expr(&format!("window.location.href = '{}'", url.replace('\'', "\\'")))
.await?;
Ok(None)
}
}
// ── Waiting ──────────────────────────────────────────────────────────
/// Wait for a selector within this frame.
///
/// # Errors
///
/// Returns an error if the element is not found within the timeout.
pub async fn wait_for_selector(&self, selector: &str, opts: WaitOptions) -> Result<()> {
self.locator(selector, None).wait_for(opts).await
}
/// Whether this frame has been detached from the page. Sync -- reads
/// the cached `detached` flag maintained by the page's frame event
/// listener. Playwright:
/// [`frame.isDetached()`](https://playwright.dev/docs/api/class-frame#frame-is-detached).
#[must_use]
pub fn is_detached(&self) -> bool {
self
.page
.with_frame_cache(|c| c.record(&self.id).is_none_or(|r| r.detached))
}
/// Get the page this frame belongs to.
#[must_use]
pub fn page(&self) -> &Page {
&self.page
}
/// Reference to the owning `Arc<Page>`. Locators hold a `Frame` and
/// reach the backend through `frame.page_arc()`.
#[must_use]
pub fn page_arc(&self) -> &Arc<Page> {
&self.page
}
/// Backend frame id (CDP/BiDi). Stable through navigations; used to
/// scope evaluation to this frame's execution context.
#[must_use]
pub fn id(&self) -> &Arc<str> {
&self.id
}
/// Set the HTML content of this frame.
///
/// # Errors
///
/// Returns an error if JS evaluation fails.
pub async fn set_content(&self, html: &str) -> Result<()> {
let escaped = crate::steps::js_escape(html);
self
.backend_eval_expr(&format!("document.documentElement.innerHTML = '{escaped}'"))
.await?;
Ok(())
}
/// Add a `<script>` tag to this frame.
///
/// # Errors
///
/// Returns an error if script injection fails.
pub async fn add_script_tag(
&self,
url: Option<&str>,
content: Option<&str>,
script_type: Option<&str>,
) -> Result<()> {
let t = script_type.unwrap_or("text/javascript");
if let Some(url) = url {
self.backend_eval_expr(&format!(
"(function(){{return new Promise(function(r,j){{var s=document.createElement('script');\
s.type='{}';s.src='{}';s.onload=r;s.onerror=function(){{j(new Error('Failed'))}};document.head.appendChild(s)}})}})();",
crate::steps::js_escape(t), crate::steps::js_escape(url)
)).await?;
} else if let Some(content) = content {
self.backend_eval_expr(&format!(
"(function(){{var s=document.createElement('script');s.type='{}';s.text='{}';document.head.appendChild(s)}})()",
crate::steps::js_escape(t), crate::steps::js_escape(content)
)).await?;
}
Ok(())
}
/// Add a `<style>` tag or `<link>` stylesheet to this frame.
///
/// # Errors
///
/// Returns an error if style injection fails.
pub async fn add_style_tag(&self, url: Option<&str>, content: Option<&str>) -> Result<()> {
if let Some(url) = url {
self.backend_eval_expr(&format!(
"(function(){{return new Promise(function(r,j){{var l=document.createElement('link');\
l.rel='stylesheet';l.href='{}';l.onload=r;l.onerror=function(){{j(new Error('Failed'))}};document.head.appendChild(l)}})}})();",
crate::steps::js_escape(url)
)).await?;
} else if let Some(content) = content {
self
.backend_eval_expr(&format!(
"(function(){{var s=document.createElement('style');s.textContent='{}';document.head.appendChild(s)}})()",
crate::steps::js_escape(content)
))
.await?;
}
Ok(())
}
/// Wait for the frame to reach a specific load state.
///
/// # Errors
///
/// Returns an error if the frame does not reach load state within the timeout.
pub async fn wait_for_load_state(&self) -> Result<()> {
if self.is_main_frame() {
self.page.wait_for_load_state(None).await
} else {
// For iframes, check document.readyState via JS
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
loop {
if tokio::time::Instant::now() >= deadline {
return Err(crate::error::FerriError::timeout(
"waiting for frame load state",
30_000,
));
}
if let Ok(Some(v)) = self.backend_eval_expr("document.readyState").await {
if v.as_str() == Some("complete") {
return Ok(());
}
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
}
}
// ── Action methods (Playwright parity — task 3.9) ──────────────────────
//
// Mirrors Playwright's frame action surface from
// `/tmp/playwright/packages/playwright-core/src/client/frame.ts:296-447`.
// Each method delegates to `self.locator(selector, None).<action>()` —
// Frame's locator already scopes by `frame_id`, so the action runs in
// the iframe's execution context (CDP) or against the synthesized
// iframe (WebKit). Option bags are intentionally minimal here; they
// ride on top of the existing Locator surface and pick up extensions
// (timeout/force/etc.) when those land on Locator itself.
// -- Mouse / pointer ---------------------------------------------------
/// Click the element matched by `selector`. Accepts Playwright's full
/// `FrameClickOptions` bag (see [`crate::options::ClickOptions`]).
///
/// # Errors
///
/// Returns an error if the element is not found or the click fails.
pub async fn click(&self, selector: &str, opts: Option<crate::options::ClickOptions>) -> Result<()> {
self.locator(selector, None).click(opts).await
}
/// Double-click the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or the dblclick fails.
pub async fn dblclick(&self, selector: &str, opts: Option<crate::options::DblClickOptions>) -> Result<()> {
self.locator(selector, None).dblclick(opts).await
}
/// Hover the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or the hover fails.
pub async fn hover(&self, selector: &str, opts: Option<crate::options::HoverOptions>) -> Result<()> {
self.locator(selector, None).hover(opts).await
}
/// Tap (touch) the element matched by `selector`. Mirrors
/// `frame.tap(selector, options?)` per
/// `/tmp/playwright/packages/playwright-core/src/client/frame.ts:308`.
///
/// # Errors
///
/// Returns an error if the element is not found or the tap fails.
pub async fn tap(&self, selector: &str, opts: Option<crate::options::TapOptions>) -> Result<()> {
self.locator(selector, None).tap(opts).await
}
/// Focus the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or focus fails.
pub async fn focus(&self, selector: &str) -> Result<()> {
self.locator(selector, None).focus().await
}
// -- Form input --------------------------------------------------------
/// Fill an input matching `selector` with `value`.
///
/// # Errors
///
/// Returns an error if the element is not found or is not fillable.
pub async fn fill(&self, selector: &str, value: &str, opts: Option<crate::options::FillOptions>) -> Result<()> {
self.locator(selector, None).fill(value, opts).await
}
/// Type characters into an element matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or typing fails.
pub async fn r#type(&self, selector: &str, text: &str, opts: Option<crate::options::TypeOptions>) -> Result<()> {
self.locator(selector, None).r#type(text, opts).await
}
/// Press a key on an element matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or the key press fails.
pub async fn press(&self, selector: &str, key: &str, opts: Option<crate::options::PressOptions>) -> Result<()> {
self.locator(selector, None).press(key, opts).await
}
/// Check a checkbox/radio matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or is not checkable.
pub async fn check(&self, selector: &str, opts: Option<crate::options::CheckOptions>) -> Result<()> {
self.locator(selector, None).check(opts).await
}
/// Uncheck a checkbox matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or is not uncheckable.
pub async fn uncheck(&self, selector: &str, opts: Option<crate::options::CheckOptions>) -> Result<()> {
self.locator(selector, None).uncheck(opts).await
}
/// Set the checked state of a checkbox/radio matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or is not checkable.
pub async fn set_checked(
&self,
selector: &str,
checked: bool,
opts: Option<crate::options::CheckOptions>,
) -> Result<()> {
self.locator(selector, None).set_checked(checked, opts).await
}
/// Select a `<select>` option in the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or the option cannot
/// be selected.
pub async fn select_option(
&self,
selector: &str,
values: Vec<crate::options::SelectOptionValue>,
opts: Option<crate::options::SelectOptionOptions>,
) -> Result<Vec<String>> {
self.locator(selector, None).select_option(values, opts).await
}
/// Set input files on a `<input type=file>` matching `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or file setting fails.
pub async fn set_input_files(
&self,
selector: &str,
files: crate::options::InputFiles,
opts: Option<crate::options::SetInputFilesOptions>,
) -> Result<()> {
self.locator(selector, None).set_input_files(files, opts).await
}
// -- Drag and drop -----------------------------------------------------
/// Drag from `source` to `target` selectors within this frame. Mirrors
/// `frame.dragAndDrop(source, target, options?)` per
/// `/tmp/playwright/packages/playwright-core/src/client/frame.ts:304`.
///
/// # Errors
///
/// Returns an error if either element cannot be found or the
/// drag-and-drop operation fails.
pub async fn drag_and_drop(
&self,
source: &str,
target: &str,
options: Option<crate::options::DragAndDropOptions>,
) -> Result<()> {
let opts = options.unwrap_or_default();
let src = self.locator(source, None);
let tgt = self.locator(target, None);
let (src, tgt) = match opts.strict {
Some(s) => (src.strict(s), tgt.strict(s)),
None => (src, tgt),
};
src.drag_to(&tgt, Some(opts)).await
}
// -- Synthetic events --------------------------------------------------
/// Dispatch a DOM event on the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found or the dispatch fails.
pub async fn dispatch_event(
&self,
selector: &str,
event_type: &str,
event_init: Option<serde_json::Value>,
opts: Option<crate::options::DispatchEventOptions>,
) -> Result<()> {
self
.locator(selector, None)
.dispatch_event(event_type, event_init, opts)
.await
}
// -- Content / attribute reads ----------------------------------------
/// Get the text content of the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn text_content(&self, selector: &str) -> Result<Option<String>> {
self.locator(selector, None).text_content().await
}
/// Get `innerText` of the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn inner_text(&self, selector: &str) -> Result<String> {
self.locator(selector, None).inner_text().await
}
/// Get `innerHTML` of the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn inner_html(&self, selector: &str) -> Result<String> {
self.locator(selector, None).inner_html().await
}
/// Get an attribute on the element matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn get_attribute(&self, selector: &str, name: &str) -> Result<Option<String>> {
self.locator(selector, None).get_attribute(name).await
}
/// Get `value` from a form control matched by `selector`.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn input_value(&self, selector: &str) -> Result<String> {
self.locator(selector, None).input_value().await
}
// -- State checks ------------------------------------------------------
/// True if the element matched by `selector` is visible.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_visible(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_visible().await
}
/// True if the element matched by `selector` is hidden.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_hidden(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_hidden().await
}
/// True if the element matched by `selector` is enabled.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_enabled(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_enabled().await
}
/// True if the element matched by `selector` is disabled.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_disabled(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_disabled().await
}
/// True if the element matched by `selector` is editable.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_editable(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_editable().await
}
/// True if a checkbox/radio matched by `selector` is checked.
///
/// # Errors
///
/// Returns an error if the element is not found.
pub async fn is_checked(&self, selector: &str) -> Result<bool> {
self.locator(selector, None).is_checked().await
}
}
impl std::fmt::Debug for Frame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (name, url, main) = self.page.with_frame_cache(|c| {
let rec = c.record(&self.id);
(
rec.map(|r| r.info.name.clone()),
rec.map(|r| r.info.url.clone()),
c.main_frame_id().as_deref() == Some(&*self.id),
)
});
f.debug_struct("Frame")
.field("id", &self.id)
.field("name", &name)
.field("url", &url)
.field("main", &main)
.finish_non_exhaustive()
}
}