chromiumoxide/handler/
frame.rs

1use std::collections::VecDeque;
2use std::collections::{HashMap, HashSet};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use serde_json::map::Entry;
7
8use chromiumoxide_cdp::cdp::browser_protocol::network::LoaderId;
9use chromiumoxide_cdp::cdp::browser_protocol::page::{
10    AddScriptToEvaluateOnNewDocumentParams, CreateIsolatedWorldParams, EventFrameDetached,
11    EventFrameStartedLoading, EventFrameStoppedLoading, EventLifecycleEvent,
12    EventNavigatedWithinDocument, Frame as CdpFrame, FrameTree,
13};
14use chromiumoxide_cdp::cdp::browser_protocol::target::EventAttachedToTarget;
15use chromiumoxide_cdp::cdp::js_protocol::runtime::*;
16use chromiumoxide_cdp::cdp::{
17    browser_protocol::page::{self, FrameId},
18    // js_protocol::runtime,
19};
20use chromiumoxide_types::{Method, MethodId, Request};
21use spider_fingerprint::BASE_CHROME_VERSION;
22
23use crate::error::DeadlineExceeded;
24use crate::handler::domworld::DOMWorld;
25use crate::handler::http::HttpRequest;
26use crate::handler::REQUEST_TIMEOUT;
27use crate::{cmd::CommandChain, ArcHttpRequest};
28
29lazy_static::lazy_static! {
30    /// Spoof the runtime.
31    static ref EVALUATION_SCRIPT_URL: String = format!("____{}___evaluation_script__", random_world_name(&BASE_CHROME_VERSION.to_string()));
32}
33
34/// Generate a collision-resistant world name using `id` + randomness.
35pub fn random_world_name(id: &str) -> String {
36    use rand::Rng;
37    let mut rng = rand::rng();
38    let rand_len = rng.random_range(6..=12);
39
40    // Convert first few chars of id into base36-compatible chars
41    let id_part: String = id
42        .chars()
43        .filter(|c| c.is_ascii_alphanumeric())
44        .take(5)
45        .map(|c| {
46            let c = c.to_ascii_lowercase();
47            if c.is_ascii_alphabetic() {
48                c
49            } else {
50                // convert 0-9 into a base36 letter offset to obscure it a bit
51                (b'a' + (c as u8 - b'0') % 26) as char
52            }
53        })
54        .collect();
55
56    // Generate random base36 tail
57    let rand_part: String = (0..rand_len)
58        .filter_map(|_| std::char::from_digit(rng.random_range(0..36), 36))
59        .collect();
60
61    // Ensure first char is always a letter (10–35 => a–z)
62    let first = std::char::from_digit(rng.random_range(10..36), 36).unwrap_or('a');
63
64    format!("{first}{id_part}{rand_part}")
65}
66
67/// Represents a frame on the page
68#[derive(Debug)]
69pub struct Frame {
70    /// The parent frame ID.
71    parent_frame: Option<FrameId>,
72    /// Cdp identifier of this frame
73    id: FrameId,
74    /// The main world.
75    main_world: DOMWorld,
76    /// The secondary world.
77    secondary_world: DOMWorld,
78    loader_id: Option<LoaderId>,
79    /// Current url of this frame
80    url: Option<String>,
81    /// The http request that loaded this with this frame
82    http_request: ArcHttpRequest,
83    /// The frames contained in this frame
84    child_frames: HashSet<FrameId>,
85    name: Option<String>,
86    /// The received lifecycle events
87    lifecycle_events: HashSet<MethodId>,
88    /// The isolated world name.
89    isolated_world_name: String,
90}
91
92impl Frame {
93    pub fn new(id: FrameId) -> Self {
94        let isolated_world_name = random_world_name(id.inner());
95
96        Self {
97            parent_frame: None,
98            id,
99            main_world: Default::default(),
100            secondary_world: Default::default(),
101            loader_id: None,
102            url: None,
103            http_request: None,
104            child_frames: Default::default(),
105            name: None,
106            lifecycle_events: Default::default(),
107            isolated_world_name,
108        }
109    }
110
111    pub fn with_parent(id: FrameId, parent: &mut Frame) -> Self {
112        parent.child_frames.insert(id.clone());
113        Self {
114            parent_frame: Some(parent.id.clone()),
115            id,
116            main_world: Default::default(),
117            secondary_world: Default::default(),
118            loader_id: None,
119            url: None,
120            http_request: None,
121            child_frames: Default::default(),
122            name: None,
123            lifecycle_events: Default::default(),
124            isolated_world_name: parent.isolated_world_name.clone(),
125        }
126    }
127
128    pub fn get_isolated_world_name(&self) -> &String {
129        &self.isolated_world_name
130    }
131
132    pub fn parent_id(&self) -> Option<&FrameId> {
133        self.parent_frame.as_ref()
134    }
135
136    pub fn id(&self) -> &FrameId {
137        &self.id
138    }
139
140    pub fn url(&self) -> Option<&str> {
141        self.url.as_deref()
142    }
143
144    pub fn name(&self) -> Option<&str> {
145        self.name.as_deref()
146    }
147
148    pub fn main_world(&self) -> &DOMWorld {
149        &self.main_world
150    }
151
152    pub fn secondary_world(&self) -> &DOMWorld {
153        &self.secondary_world
154    }
155
156    pub fn lifecycle_events(&self) -> &HashSet<MethodId> {
157        &self.lifecycle_events
158    }
159
160    pub fn http_request(&self) -> Option<&Arc<HttpRequest>> {
161        self.http_request.as_ref()
162    }
163
164    fn navigated(&mut self, frame: &CdpFrame) {
165        self.name.clone_from(&frame.name);
166        let url = if let Some(ref fragment) = frame.url_fragment {
167            format!("{}{fragment}", frame.url)
168        } else {
169            frame.url.clone()
170        };
171        self.url = Some(url);
172    }
173
174    fn navigated_within_url(&mut self, url: String) {
175        self.url = Some(url)
176    }
177
178    fn on_loading_stopped(&mut self) {
179        self.lifecycle_events.insert("DOMContentLoaded".into());
180        self.lifecycle_events.insert("load".into());
181    }
182
183    fn on_loading_started(&mut self) {
184        self.lifecycle_events.clear();
185        self.http_request.take();
186    }
187
188    pub fn is_loaded(&self) -> bool {
189        self.lifecycle_events.contains("load")
190    }
191
192    /// Main frame + child frames have fired the `networkIdle` lifecycle event.
193    pub fn is_network_idle(&self) -> bool {
194        self.lifecycle_events.contains("networkIdle")
195    }
196
197    /// Main frame + child frames have fired the `networkAlmostIdle` lifecycle event.
198    pub fn is_network_almost_idle(&self) -> bool {
199        self.lifecycle_events.contains("networkAlmostIdle")
200    }
201
202    pub fn clear_contexts(&mut self) {
203        self.main_world.take_context();
204        self.secondary_world.take_context();
205    }
206
207    pub fn destroy_context(&mut self, ctx_unique_id: &str) {
208        if self.main_world.execution_context_unique_id() == Some(ctx_unique_id) {
209            self.main_world.take_context();
210        } else if self.secondary_world.execution_context_unique_id() == Some(ctx_unique_id) {
211            self.secondary_world.take_context();
212        }
213    }
214
215    pub fn execution_context(&self) -> Option<ExecutionContextId> {
216        self.main_world.execution_context()
217    }
218
219    pub fn set_request(&mut self, request: HttpRequest) {
220        self.http_request = Some(Arc::new(request))
221    }
222}
223
224/// Maintains the state of the pages frame and listens to events produced by
225/// chromium targeting the `Target`. Also listens for events that indicate that
226/// a navigation was completed
227#[derive(Debug)]
228pub struct FrameManager {
229    main_frame: Option<FrameId>,
230    frames: HashMap<FrameId, Frame>,
231    /// The contexts mapped with their frames
232    context_ids: HashMap<String, FrameId>,
233    isolated_worlds: HashSet<String>,
234    /// Timeout after which an anticipated event (related to navigation) doesn't
235    /// arrive results in an error
236    request_timeout: Duration,
237    /// Track currently in progress navigation
238    pending_navigations: VecDeque<(FrameRequestedNavigation, NavigationWatcher)>,
239    /// The currently ongoing navigation
240    navigation: Option<(NavigationWatcher, Instant)>,
241}
242
243impl FrameManager {
244    pub fn new(request_timeout: Duration) -> Self {
245        FrameManager {
246            main_frame: None,
247            frames: Default::default(),
248            context_ids: Default::default(),
249            isolated_worlds: Default::default(),
250            request_timeout,
251            pending_navigations: Default::default(),
252            navigation: None,
253        }
254    }
255
256    /// The commands to execute in order to initialize this frame manager
257    pub fn init_commands(timeout: Duration) -> CommandChain {
258        let enable = page::EnableParams::default();
259        let get_tree = page::GetFrameTreeParams::default();
260        let set_lifecycle = page::SetLifecycleEventsEnabledParams::new(true);
261        // let enable_runtime = EnableParams::default();
262        // let disable_runtime = DisableParams::default();
263
264        let mut commands = Vec::with_capacity(3);
265
266        let enable_id = enable.identifier();
267        let get_tree_id = get_tree.identifier();
268        let set_lifecycle_id = set_lifecycle.identifier();
269        // let enable_runtime_id = enable_runtime.identifier();
270        // let disable_runtime_id = disable_runtime.identifier();
271
272        if let Ok(value) = serde_json::to_value(enable) {
273            commands.push((enable_id, value));
274        }
275
276        if let Ok(value) = serde_json::to_value(get_tree) {
277            commands.push((get_tree_id, value));
278        }
279
280        if let Ok(value) = serde_json::to_value(set_lifecycle) {
281            commands.push((set_lifecycle_id, value));
282        }
283
284        // if let Ok(value) = serde_json::to_value(enable_runtime) {
285        //     commands.push((enable_runtime_id, value));
286        // }
287
288        // if let Ok(value) = serde_json::to_value(disable_runtime) {
289        //     commands.push((disable_runtime_id, value));
290        // }
291
292        CommandChain::new(commands, timeout)
293    }
294
295    pub fn main_frame(&self) -> Option<&Frame> {
296        self.main_frame.as_ref().and_then(|id| self.frames.get(id))
297    }
298
299    pub fn main_frame_mut(&mut self) -> Option<&mut Frame> {
300        if let Some(id) = self.main_frame.as_ref() {
301            self.frames.get_mut(id)
302        } else {
303            None
304        }
305    }
306
307    /// Get the main isolated world name.
308    pub fn get_isolated_world_name(&self) -> Option<&String> {
309        self.main_frame
310            .as_ref()
311            .and_then(|id| match self.frames.get(id) {
312                Some(fid) => Some(fid.get_isolated_world_name()),
313                _ => None,
314            })
315    }
316
317    pub fn frames(&self) -> impl Iterator<Item = &Frame> + '_ {
318        self.frames.values()
319    }
320
321    pub fn frame(&self, id: &FrameId) -> Option<&Frame> {
322        self.frames.get(id)
323    }
324
325    fn check_lifecycle(&self, watcher: &NavigationWatcher, frame: &Frame) -> bool {
326        watcher.expected_lifecycle.iter().all(|ev| {
327            frame.lifecycle_events.contains(ev)
328                || (frame.url.is_none() && frame.lifecycle_events.contains("DOMContentLoaded"))
329        }) && frame
330            .child_frames
331            .iter()
332            .filter_map(|f| self.frames.get(f))
333            .all(|f| self.check_lifecycle(watcher, f))
334    }
335
336    fn check_lifecycle_complete(
337        &self,
338        watcher: &NavigationWatcher,
339        frame: &Frame,
340    ) -> Option<NavigationOk> {
341        if !self.check_lifecycle(watcher, frame) {
342            return None;
343        }
344        if frame.loader_id == watcher.loader_id && !watcher.same_document_navigation {
345            return None;
346        }
347        if watcher.same_document_navigation {
348            return Some(NavigationOk::SameDocumentNavigation(watcher.id));
349        }
350        if frame.loader_id != watcher.loader_id {
351            return Some(NavigationOk::NewDocumentNavigation(watcher.id));
352        }
353        None
354    }
355
356    /// Track the request in the frame
357    pub fn on_http_request_finished(&mut self, request: HttpRequest) {
358        if let Some(id) = request.frame.as_ref() {
359            if let Some(frame) = self.frames.get_mut(id) {
360                frame.set_request(request);
361            }
362        }
363    }
364
365    pub fn poll(&mut self, now: Instant) -> Option<FrameEvent> {
366        // check if the navigation completed
367        if let Some((watcher, deadline)) = self.navigation.take() {
368            if now > deadline {
369                // navigation request timed out
370                return Some(FrameEvent::NavigationResult(Err(
371                    NavigationError::Timeout {
372                        err: DeadlineExceeded::new(now, deadline),
373                        id: watcher.id,
374                    },
375                )));
376            }
377
378            if let Some(frame) = self.frames.get(&watcher.frame_id) {
379                if let Some(nav) = self.check_lifecycle_complete(&watcher, frame) {
380                    // request is complete if the frame's lifecycle is complete = frame received all
381                    // required events
382                    return Some(FrameEvent::NavigationResult(Ok(nav)));
383                } else {
384                    // not finished yet
385                    self.navigation = Some((watcher, deadline));
386                }
387            } else {
388                return Some(FrameEvent::NavigationResult(Err(
389                    NavigationError::FrameNotFound {
390                        frame: watcher.frame_id,
391                        id: watcher.id,
392                    },
393                )));
394            }
395        } else if let Some((req, watcher)) = self.pending_navigations.pop_front() {
396            // queue in the next navigation that is must be fulfilled until `deadline`
397            let deadline = Instant::now() + req.timeout;
398            self.navigation = Some((watcher, deadline));
399            return Some(FrameEvent::NavigationRequest(req.id, req.req));
400        }
401        None
402    }
403
404    /// Entrypoint for page navigation
405    pub fn goto(&mut self, req: FrameRequestedNavigation) {
406        if let Some(frame_id) = &self.main_frame {
407            self.navigate_frame(frame_id.clone(), req);
408        }
409    }
410
411    /// Navigate a specific frame
412    pub fn navigate_frame(&mut self, frame_id: FrameId, mut req: FrameRequestedNavigation) {
413        let loader_id = self.frames.get(&frame_id).and_then(|f| f.loader_id.clone());
414        let watcher = NavigationWatcher::until_load(req.id, frame_id.clone(), loader_id);
415
416        // insert the frame_id in the request if not present
417        req.set_frame_id(frame_id);
418
419        self.pending_navigations.push_back((req, watcher))
420    }
421
422    /// Fired when a frame moved to another session
423    pub fn on_attached_to_target(&mut self, _event: &EventAttachedToTarget) {
424        // _onFrameMoved
425    }
426
427    pub fn on_frame_tree(&mut self, frame_tree: FrameTree) {
428        self.on_frame_attached(
429            frame_tree.frame.id.clone(),
430            frame_tree.frame.parent_id.clone().map(Into::into),
431        );
432        self.on_frame_navigated(&frame_tree.frame);
433        if let Some(children) = frame_tree.child_frames {
434            for child_tree in children {
435                self.on_frame_tree(child_tree);
436            }
437        }
438    }
439
440    pub fn on_frame_attached(&mut self, frame_id: FrameId, parent_frame_id: Option<FrameId>) {
441        if self.frames.contains_key(&frame_id) {
442            return;
443        }
444        if let Some(parent_frame_id) = parent_frame_id {
445            if let Some(parent_frame) = self.frames.get_mut(&parent_frame_id) {
446                let frame = Frame::with_parent(frame_id.clone(), parent_frame);
447                self.frames.insert(frame_id, frame);
448            }
449        }
450    }
451
452    pub fn on_frame_detached(&mut self, event: &EventFrameDetached) {
453        self.remove_frames_recursively(&event.frame_id);
454    }
455
456    pub fn on_frame_navigated(&mut self, frame: &CdpFrame) {
457        if frame.parent_id.is_some() {
458            if let Some((id, mut f)) = self.frames.remove_entry(&frame.id) {
459                for child in f.child_frames.drain() {
460                    self.remove_frames_recursively(&child);
461                }
462                f.navigated(frame);
463                self.frames.insert(id, f);
464            }
465        } else {
466            let mut f = if let Some(main) = self.main_frame.take() {
467                // update main frame
468                if let Some(mut main_frame) = self.frames.remove(&main) {
469                    for child in &main_frame.child_frames {
470                        self.remove_frames_recursively(child);
471                    }
472                    // this is necessary since we can't borrow mut and then remove recursively
473                    main_frame.child_frames.clear();
474                    main_frame.id = frame.id.clone();
475                    main_frame
476                } else {
477                    Frame::new(frame.id.clone())
478                }
479            } else {
480                // initial main frame navigation
481                Frame::new(frame.id.clone())
482            };
483            f.navigated(frame);
484            self.main_frame = Some(f.id.clone());
485            self.frames.insert(f.id.clone(), f);
486        }
487    }
488
489    pub fn on_frame_navigated_within_document(&mut self, event: &EventNavigatedWithinDocument) {
490        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
491            frame.navigated_within_url(event.url.clone());
492        }
493        if let Some((watcher, _)) = self.navigation.as_mut() {
494            watcher.on_frame_navigated_within_document(event);
495        }
496    }
497
498    pub fn on_frame_stopped_loading(&mut self, event: &EventFrameStoppedLoading) {
499        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
500            frame.on_loading_stopped();
501        }
502    }
503
504    /// Fired when frame has started loading.
505    pub fn on_frame_started_loading(&mut self, event: &EventFrameStartedLoading) {
506        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
507            frame.on_loading_started();
508        }
509    }
510
511    /// Notification is issued every time when binding is called
512    pub fn on_runtime_binding_called(&mut self, _ev: &EventBindingCalled) {}
513
514    /// Issued when new execution context is created
515    pub fn on_frame_execution_context_created(&mut self, event: &EventExecutionContextCreated) {
516        if let Some(frame_id) = event
517            .context
518            .aux_data
519            .as_ref()
520            .and_then(|v| v["frameId"].as_str())
521        {
522            if let Some(frame) = self.frames.get_mut(frame_id) {
523                if event
524                    .context
525                    .aux_data
526                    .as_ref()
527                    .and_then(|v| v["isDefault"].as_bool())
528                    .unwrap_or_default()
529                {
530                    frame
531                        .main_world
532                        .set_context(event.context.id, event.context.unique_id.clone());
533                } else if event.context.name == frame.isolated_world_name
534                    && frame.secondary_world.execution_context().is_none()
535                {
536                    frame
537                        .secondary_world
538                        .set_context(event.context.id, event.context.unique_id.clone());
539                }
540                self.context_ids
541                    .insert(event.context.unique_id.clone(), frame.id.clone());
542            }
543        }
544        if event
545            .context
546            .aux_data
547            .as_ref()
548            .filter(|v| v["type"].as_str() == Some("isolated"))
549            .is_some()
550        {
551            self.isolated_worlds.insert(event.context.name.clone());
552        }
553    }
554
555    /// Issued when execution context is destroyed
556    pub fn on_frame_execution_context_destroyed(&mut self, event: &EventExecutionContextDestroyed) {
557        if let Some(id) = self.context_ids.remove(&event.execution_context_unique_id) {
558            if let Some(frame) = self.frames.get_mut(&id) {
559                frame.destroy_context(&event.execution_context_unique_id);
560            }
561        }
562    }
563
564    /// Issued when all executionContexts were cleared
565    pub fn on_execution_contexts_cleared(&mut self) {
566        for id in self.context_ids.values() {
567            if let Some(frame) = self.frames.get_mut(id) {
568                frame.clear_contexts();
569            }
570        }
571        self.context_ids.clear()
572    }
573
574    /// Fired for top level page lifecycle events (nav, load, paint, etc.)
575    pub fn on_page_lifecycle_event(&mut self, event: &EventLifecycleEvent) {
576        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
577            if event.name == "init" {
578                frame.loader_id = Some(event.loader_id.clone());
579                frame.lifecycle_events.clear();
580            }
581            frame.lifecycle_events.insert(event.name.clone().into());
582        }
583    }
584
585    /// Detach all child frames
586    fn remove_frames_recursively(&mut self, id: &FrameId) -> Option<Frame> {
587        if let Some(mut frame) = self.frames.remove(id) {
588            for child in &frame.child_frames {
589                self.remove_frames_recursively(child);
590            }
591            if let Some(parent_id) = frame.parent_frame.take() {
592                if let Some(parent) = self.frames.get_mut(&parent_id) {
593                    parent.child_frames.remove(&frame.id);
594                }
595            }
596            Some(frame)
597        } else {
598            None
599        }
600    }
601
602    pub fn ensure_isolated_world(&mut self, world_name: &str) -> Option<CommandChain> {
603        if self.isolated_worlds.contains(world_name) {
604            return None;
605        }
606
607        self.isolated_worlds.insert(world_name.to_string());
608
609        if let Ok(cmd) = AddScriptToEvaluateOnNewDocumentParams::builder()
610            .source(format!("//# sourceURL={}", *EVALUATION_SCRIPT_URL))
611            .world_name(world_name)
612            .build()
613        {
614            let mut cmds = Vec::with_capacity(self.frames.len() + 1);
615            let identifier = cmd.identifier();
616
617            if let Ok(cmd) = serde_json::to_value(cmd) {
618                cmds.push((identifier, cmd));
619            }
620
621            let cm = self.frames.keys().filter_map(|id| {
622                if let Ok(cmd) = CreateIsolatedWorldParams::builder()
623                    .frame_id(id.clone())
624                    .grant_univeral_access(true)
625                    .world_name(world_name)
626                    .build()
627                {
628                    let cm = (
629                        cmd.identifier(),
630                        serde_json::to_value(cmd).unwrap_or_default(),
631                    );
632
633                    Some(cm)
634                } else {
635                    None
636                }
637            });
638
639            cmds.extend(cm);
640
641            Some(CommandChain::new(cmds, self.request_timeout))
642        } else {
643            None
644        }
645    }
646}
647
648#[derive(Debug)]
649pub enum FrameEvent {
650    /// A previously submitted navigation has finished
651    NavigationResult(Result<NavigationOk, NavigationError>),
652    /// A new navigation request needs to be submitted
653    NavigationRequest(NavigationId, Request),
654    /* /// The initial page of the target has been loaded
655     * InitialPageLoadFinished */
656}
657
658#[derive(Debug)]
659pub enum NavigationError {
660    Timeout {
661        id: NavigationId,
662        err: DeadlineExceeded,
663    },
664    FrameNotFound {
665        id: NavigationId,
666        frame: FrameId,
667    },
668}
669
670impl NavigationError {
671    pub fn navigation_id(&self) -> &NavigationId {
672        match self {
673            NavigationError::Timeout { id, .. } => id,
674            NavigationError::FrameNotFound { id, .. } => id,
675        }
676    }
677}
678
679#[derive(Debug, Clone, Eq, PartialEq)]
680pub enum NavigationOk {
681    SameDocumentNavigation(NavigationId),
682    NewDocumentNavigation(NavigationId),
683}
684
685impl NavigationOk {
686    pub fn navigation_id(&self) -> &NavigationId {
687        match self {
688            NavigationOk::SameDocumentNavigation(id) => id,
689            NavigationOk::NewDocumentNavigation(id) => id,
690        }
691    }
692}
693
694/// Tracks the progress of an issued `Page.navigate` request until completion.
695#[derive(Debug)]
696pub struct NavigationWatcher {
697    id: NavigationId,
698    expected_lifecycle: HashSet<MethodId>,
699    frame_id: FrameId,
700    loader_id: Option<LoaderId>,
701    /// Once we receive the response to the issued `Page.navigate` request we
702    /// can detect whether we were navigating withing the same document or were
703    /// navigating to a new document by checking if a loader was included in the
704    /// response.
705    same_document_navigation: bool,
706}
707
708impl NavigationWatcher {
709    /// Generic ctor: wait until all given lifecycle events have fired
710    /// (including all child frames).
711    pub fn until_lifecycle(
712        id: NavigationId,
713        frame: FrameId,
714        loader_id: Option<LoaderId>,
715        events: &[LifecycleEvent],
716    ) -> Self {
717        let expected_lifecycle = events.iter().map(LifecycleEvent::to_method_id).collect();
718
719        Self {
720            id,
721            expected_lifecycle,
722            frame_id: frame,
723            loader_id,
724            same_document_navigation: false,
725        }
726    }
727
728    /// Wait for "load"
729    pub fn until_load(id: NavigationId, frame: FrameId, loader_id: Option<LoaderId>) -> Self {
730        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::Load])
731    }
732
733    /// Wait for DOMContentLoaded
734    pub fn until_domcontent_loaded(
735        id: NavigationId,
736        frame: FrameId,
737        loader_id: Option<LoaderId>,
738    ) -> Self {
739        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::DomcontentLoaded])
740    }
741
742    /// Wait for networkIdle
743    pub fn until_network_idle(
744        id: NavigationId,
745        frame: FrameId,
746        loader_id: Option<LoaderId>,
747    ) -> Self {
748        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::NetworkIdle])
749    }
750
751    /// Wait for networkAlmostIdle
752    pub fn until_network_almost_idle(
753        id: NavigationId,
754        frame: FrameId,
755        loader_id: Option<LoaderId>,
756    ) -> Self {
757        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::NetworkAlmostIdle])
758    }
759
760    /// (optional) Wait for multiple states, e.g. DOMContentLoaded + networkIdle
761    pub fn until_domcontent_and_network_idle(
762        id: NavigationId,
763        frame: FrameId,
764        loader_id: Option<LoaderId>,
765    ) -> Self {
766        Self::until_lifecycle(
767            id,
768            frame,
769            loader_id,
770            &[
771                LifecycleEvent::DomcontentLoaded,
772                LifecycleEvent::NetworkIdle,
773            ],
774        )
775    }
776
777    /// Checks whether the navigation was completed
778    pub fn is_lifecycle_complete(&self) -> bool {
779        self.expected_lifecycle.is_empty()
780    }
781
782    fn on_frame_navigated_within_document(&mut self, ev: &EventNavigatedWithinDocument) {
783        if self.frame_id == ev.frame_id {
784            self.same_document_navigation = true;
785        }
786    }
787}
788
789/// An identifier for an ongoing navigation
790#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
791pub struct NavigationId(pub usize);
792
793/// Represents a the request for a navigation
794#[derive(Debug)]
795pub struct FrameRequestedNavigation {
796    /// The internal identifier
797    pub id: NavigationId,
798    /// the cdp request that will trigger the navigation
799    pub req: Request,
800    /// The timeout after which the request will be considered timed out
801    pub timeout: Duration,
802}
803
804impl FrameRequestedNavigation {
805    pub fn new(id: NavigationId, req: Request) -> Self {
806        Self {
807            id,
808            req,
809            timeout: Duration::from_millis(REQUEST_TIMEOUT),
810        }
811    }
812
813    /// This will set the id of the frame into the `params` `frameId` field.
814    pub fn set_frame_id(&mut self, frame_id: FrameId) {
815        if let Some(params) = self.req.params.as_object_mut() {
816            if let Entry::Vacant(entry) = params.entry("frameId") {
817                entry.insert(serde_json::Value::String(frame_id.into()));
818            }
819        }
820    }
821}
822
823#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
824pub enum LifecycleEvent {
825    #[default]
826    Load,
827    DomcontentLoaded,
828    NetworkIdle,
829    NetworkAlmostIdle,
830}
831
832impl LifecycleEvent {
833    #[inline]
834    pub fn to_method_id(&self) -> MethodId {
835        match self {
836            LifecycleEvent::Load => "load".into(),
837            LifecycleEvent::DomcontentLoaded => "DOMContentLoaded".into(),
838            LifecycleEvent::NetworkIdle => "networkIdle".into(),
839            LifecycleEvent::NetworkAlmostIdle => "networkAlmostIdle".into(),
840        }
841    }
842}
843
844impl AsRef<str> for LifecycleEvent {
845    fn as_ref(&self) -> &str {
846        match self {
847            LifecycleEvent::Load => "load",
848            LifecycleEvent::DomcontentLoaded => "DOMContentLoaded",
849            LifecycleEvent::NetworkIdle => "networkIdle",
850            LifecycleEvent::NetworkAlmostIdle => "networkAlmostIdle",
851        }
852    }
853}