Skip to main content

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;
26
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| self.frames.get(id).map(|fid| fid.get_isolated_world_name()))
312    }
313
314    pub fn frames(&self) -> impl Iterator<Item = &Frame> + '_ {
315        self.frames.values()
316    }
317
318    pub fn frame(&self, id: &FrameId) -> Option<&Frame> {
319        self.frames.get(id)
320    }
321
322    fn check_lifecycle(&self, watcher: &NavigationWatcher, frame: &Frame) -> bool {
323        watcher.expected_lifecycle.iter().all(|ev| {
324            frame.lifecycle_events.contains(ev)
325                || (frame.url.is_none() && frame.lifecycle_events.contains("DOMContentLoaded"))
326        }) && frame
327            .child_frames
328            .iter()
329            .filter_map(|f| self.frames.get(f))
330            .all(|f| self.check_lifecycle(watcher, f))
331    }
332
333    fn check_lifecycle_complete(
334        &self,
335        watcher: &NavigationWatcher,
336        frame: &Frame,
337    ) -> Option<NavigationOk> {
338        if !self.check_lifecycle(watcher, frame) {
339            return None;
340        }
341        if frame.loader_id == watcher.loader_id && !watcher.same_document_navigation {
342            return None;
343        }
344        if watcher.same_document_navigation {
345            return Some(NavigationOk::SameDocumentNavigation(watcher.id));
346        }
347        if frame.loader_id != watcher.loader_id {
348            return Some(NavigationOk::NewDocumentNavigation(watcher.id));
349        }
350        None
351    }
352
353    /// Track the request in the frame
354    pub fn on_http_request_finished(&mut self, request: HttpRequest) {
355        if let Some(id) = request.frame.as_ref() {
356            if let Some(frame) = self.frames.get_mut(id) {
357                frame.set_request(request);
358            }
359        }
360    }
361
362    pub fn poll(&mut self, now: Instant) -> Option<FrameEvent> {
363        // check if the navigation completed
364        if let Some((watcher, deadline)) = self.navigation.take() {
365            if now > deadline {
366                // navigation request timed out
367                return Some(FrameEvent::NavigationResult(Err(
368                    NavigationError::Timeout {
369                        err: DeadlineExceeded::new(now, deadline),
370                        id: watcher.id,
371                    },
372                )));
373            }
374
375            if let Some(frame) = self.frames.get(&watcher.frame_id) {
376                if let Some(nav) = self.check_lifecycle_complete(&watcher, frame) {
377                    // request is complete if the frame's lifecycle is complete = frame received all
378                    // required events
379                    return Some(FrameEvent::NavigationResult(Ok(nav)));
380                } else {
381                    // not finished yet
382                    self.navigation = Some((watcher, deadline));
383                }
384            } else {
385                return Some(FrameEvent::NavigationResult(Err(
386                    NavigationError::FrameNotFound {
387                        frame: watcher.frame_id,
388                        id: watcher.id,
389                    },
390                )));
391            }
392        } else if let Some((req, watcher)) = self.pending_navigations.pop_front() {
393            // queue in the next navigation that is must be fulfilled until `deadline`
394            let deadline = Instant::now() + req.timeout;
395            self.navigation = Some((watcher, deadline));
396            return Some(FrameEvent::NavigationRequest(req.id, req.req));
397        }
398        None
399    }
400
401    /// Entrypoint for page navigation
402    pub fn goto(&mut self, req: FrameRequestedNavigation) {
403        if let Some(frame_id) = &self.main_frame {
404            self.navigate_frame(frame_id.clone(), req);
405        }
406    }
407
408    /// Navigate a specific frame
409    pub fn navigate_frame(&mut self, frame_id: FrameId, mut req: FrameRequestedNavigation) {
410        let loader_id = self.frames.get(&frame_id).and_then(|f| f.loader_id.clone());
411        let watcher = NavigationWatcher::until_load(req.id, frame_id.clone(), loader_id);
412
413        // insert the frame_id in the request if not present
414        req.set_frame_id(frame_id);
415
416        self.pending_navigations.push_back((req, watcher))
417    }
418
419    /// Fired when a frame moved to another session
420    pub fn on_attached_to_target(&mut self, _event: &EventAttachedToTarget) {
421        // _onFrameMoved
422    }
423
424    pub fn on_frame_tree(&mut self, frame_tree: FrameTree) {
425        self.on_frame_attached(
426            frame_tree.frame.id.clone(),
427            frame_tree.frame.parent_id.clone(),
428        );
429        self.on_frame_navigated(&frame_tree.frame);
430        if let Some(children) = frame_tree.child_frames {
431            for child_tree in children {
432                self.on_frame_tree(child_tree);
433            }
434        }
435    }
436
437    pub fn on_frame_attached(&mut self, frame_id: FrameId, parent_frame_id: Option<FrameId>) {
438        if self.frames.contains_key(&frame_id) {
439            return;
440        }
441        if let Some(parent_frame_id) = parent_frame_id {
442            if let Some(parent_frame) = self.frames.get_mut(&parent_frame_id) {
443                let frame = Frame::with_parent(frame_id.clone(), parent_frame);
444                self.frames.insert(frame_id, frame);
445            }
446        }
447    }
448
449    pub fn on_frame_detached(&mut self, event: &EventFrameDetached) {
450        self.remove_frames_recursively(&event.frame_id);
451    }
452
453    pub fn on_frame_navigated(&mut self, frame: &CdpFrame) {
454        if frame.parent_id.is_some() {
455            if let Some((id, mut f)) = self.frames.remove_entry(&frame.id) {
456                for child in f.child_frames.drain() {
457                    self.remove_frames_recursively(&child);
458                }
459                f.navigated(frame);
460                self.frames.insert(id, f);
461            }
462        } else {
463            let mut f = if let Some(main) = self.main_frame.take() {
464                // update main frame
465                if let Some(mut main_frame) = self.frames.remove(&main) {
466                    for child in &main_frame.child_frames {
467                        self.remove_frames_recursively(child);
468                    }
469                    // this is necessary since we can't borrow mut and then remove recursively
470                    main_frame.child_frames.clear();
471                    main_frame.id = frame.id.clone();
472                    main_frame
473                } else {
474                    Frame::new(frame.id.clone())
475                }
476            } else {
477                // initial main frame navigation
478                Frame::new(frame.id.clone())
479            };
480            f.navigated(frame);
481            self.main_frame = Some(f.id.clone());
482            self.frames.insert(f.id.clone(), f);
483        }
484    }
485
486    pub fn on_frame_navigated_within_document(&mut self, event: &EventNavigatedWithinDocument) {
487        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
488            frame.navigated_within_url(event.url.clone());
489        }
490        if let Some((watcher, _)) = self.navigation.as_mut() {
491            watcher.on_frame_navigated_within_document(event);
492        }
493    }
494
495    pub fn on_frame_stopped_loading(&mut self, event: &EventFrameStoppedLoading) {
496        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
497            frame.on_loading_stopped();
498        }
499    }
500
501    /// Fired when frame has started loading.
502    pub fn on_frame_started_loading(&mut self, event: &EventFrameStartedLoading) {
503        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
504            frame.on_loading_started();
505        }
506    }
507
508    /// Notification is issued every time when binding is called
509    pub fn on_runtime_binding_called(&mut self, _ev: &EventBindingCalled) {}
510
511    /// Issued when new execution context is created
512    pub fn on_frame_execution_context_created(&mut self, event: &EventExecutionContextCreated) {
513        if let Some(frame_id) = event
514            .context
515            .aux_data
516            .as_ref()
517            .and_then(|v| v["frameId"].as_str())
518        {
519            if let Some(frame) = self.frames.get_mut(frame_id) {
520                if event
521                    .context
522                    .aux_data
523                    .as_ref()
524                    .and_then(|v| v["isDefault"].as_bool())
525                    .unwrap_or_default()
526                {
527                    frame
528                        .main_world
529                        .set_context(event.context.id, event.context.unique_id.clone());
530                } else if event.context.name == frame.isolated_world_name
531                    && frame.secondary_world.execution_context().is_none()
532                {
533                    frame
534                        .secondary_world
535                        .set_context(event.context.id, event.context.unique_id.clone());
536                }
537                self.context_ids
538                    .insert(event.context.unique_id.clone(), frame.id.clone());
539            }
540        }
541        if event
542            .context
543            .aux_data
544            .as_ref()
545            .filter(|v| v["type"].as_str() == Some("isolated"))
546            .is_some()
547        {
548            self.isolated_worlds.insert(event.context.name.clone());
549        }
550    }
551
552    /// Issued when execution context is destroyed
553    pub fn on_frame_execution_context_destroyed(&mut self, event: &EventExecutionContextDestroyed) {
554        if let Some(id) = self.context_ids.remove(&event.execution_context_unique_id) {
555            if let Some(frame) = self.frames.get_mut(&id) {
556                frame.destroy_context(&event.execution_context_unique_id);
557            }
558        }
559    }
560
561    /// Issued when all executionContexts were cleared
562    pub fn on_execution_contexts_cleared(&mut self) {
563        for id in self.context_ids.values() {
564            if let Some(frame) = self.frames.get_mut(id) {
565                frame.clear_contexts();
566            }
567        }
568        self.context_ids.clear()
569    }
570
571    /// Fired for top level page lifecycle events (nav, load, paint, etc.)
572    pub fn on_page_lifecycle_event(&mut self, event: &EventLifecycleEvent) {
573        if let Some(frame) = self.frames.get_mut(&event.frame_id) {
574            if event.name == "init" {
575                frame.loader_id = Some(event.loader_id.clone());
576                frame.lifecycle_events.clear();
577            }
578            frame.lifecycle_events.insert(event.name.clone().into());
579        }
580    }
581
582    /// Detach all child frames
583    fn remove_frames_recursively(&mut self, id: &FrameId) -> Option<Frame> {
584        if let Some(mut frame) = self.frames.remove(id) {
585            for child in &frame.child_frames {
586                self.remove_frames_recursively(child);
587            }
588            if let Some(parent_id) = frame.parent_frame.take() {
589                if let Some(parent) = self.frames.get_mut(&parent_id) {
590                    parent.child_frames.remove(&frame.id);
591                }
592            }
593            Some(frame)
594        } else {
595            None
596        }
597    }
598
599    pub fn ensure_isolated_world(&mut self, world_name: &str) -> Option<CommandChain> {
600        if self.isolated_worlds.contains(world_name) {
601            return None;
602        }
603
604        self.isolated_worlds.insert(world_name.to_string());
605
606        if let Ok(cmd) = AddScriptToEvaluateOnNewDocumentParams::builder()
607            .source(format!("//# sourceURL={}", *EVALUATION_SCRIPT_URL))
608            .world_name(world_name)
609            .build()
610        {
611            let mut cmds = Vec::with_capacity(self.frames.len() + 1);
612            let identifier = cmd.identifier();
613
614            if let Ok(cmd) = serde_json::to_value(cmd) {
615                cmds.push((identifier, cmd));
616            }
617
618            let cm = self.frames.keys().filter_map(|id| {
619                if let Ok(cmd) = CreateIsolatedWorldParams::builder()
620                    .frame_id(id.clone())
621                    .grant_univeral_access(true)
622                    .world_name(world_name)
623                    .build()
624                {
625                    let cm = (
626                        cmd.identifier(),
627                        serde_json::to_value(cmd).unwrap_or_default(),
628                    );
629
630                    Some(cm)
631                } else {
632                    None
633                }
634            });
635
636            cmds.extend(cm);
637
638            Some(CommandChain::new(cmds, self.request_timeout))
639        } else {
640            None
641        }
642    }
643}
644
645#[derive(Debug)]
646pub enum FrameEvent {
647    /// A previously submitted navigation has finished
648    NavigationResult(Result<NavigationOk, NavigationError>),
649    /// A new navigation request needs to be submitted
650    NavigationRequest(NavigationId, Request),
651    /* /// The initial page of the target has been loaded
652     * InitialPageLoadFinished */
653}
654
655#[derive(Debug)]
656pub enum NavigationError {
657    Timeout {
658        id: NavigationId,
659        err: DeadlineExceeded,
660    },
661    FrameNotFound {
662        id: NavigationId,
663        frame: FrameId,
664    },
665}
666
667impl NavigationError {
668    pub fn navigation_id(&self) -> &NavigationId {
669        match self {
670            NavigationError::Timeout { id, .. } => id,
671            NavigationError::FrameNotFound { id, .. } => id,
672        }
673    }
674}
675
676#[derive(Debug, Clone, Eq, PartialEq)]
677pub enum NavigationOk {
678    SameDocumentNavigation(NavigationId),
679    NewDocumentNavigation(NavigationId),
680}
681
682impl NavigationOk {
683    pub fn navigation_id(&self) -> &NavigationId {
684        match self {
685            NavigationOk::SameDocumentNavigation(id) => id,
686            NavigationOk::NewDocumentNavigation(id) => id,
687        }
688    }
689}
690
691/// Tracks the progress of an issued `Page.navigate` request until completion.
692#[derive(Debug)]
693pub struct NavigationWatcher {
694    id: NavigationId,
695    expected_lifecycle: HashSet<MethodId>,
696    frame_id: FrameId,
697    loader_id: Option<LoaderId>,
698    /// Once we receive the response to the issued `Page.navigate` request we
699    /// can detect whether we were navigating withing the same document or were
700    /// navigating to a new document by checking if a loader was included in the
701    /// response.
702    same_document_navigation: bool,
703}
704
705impl NavigationWatcher {
706    /// Generic ctor: wait until all given lifecycle events have fired
707    /// (including all child frames).
708    pub fn until_lifecycle(
709        id: NavigationId,
710        frame: FrameId,
711        loader_id: Option<LoaderId>,
712        events: &[LifecycleEvent],
713    ) -> Self {
714        let expected_lifecycle = events.iter().map(LifecycleEvent::to_method_id).collect();
715
716        Self {
717            id,
718            expected_lifecycle,
719            frame_id: frame,
720            loader_id,
721            same_document_navigation: false,
722        }
723    }
724
725    /// Wait for "load"
726    pub fn until_load(id: NavigationId, frame: FrameId, loader_id: Option<LoaderId>) -> Self {
727        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::Load])
728    }
729
730    /// Wait for DOMContentLoaded
731    pub fn until_domcontent_loaded(
732        id: NavigationId,
733        frame: FrameId,
734        loader_id: Option<LoaderId>,
735    ) -> Self {
736        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::DomcontentLoaded])
737    }
738
739    /// Wait for networkIdle
740    pub fn until_network_idle(
741        id: NavigationId,
742        frame: FrameId,
743        loader_id: Option<LoaderId>,
744    ) -> Self {
745        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::NetworkIdle])
746    }
747
748    /// Wait for networkAlmostIdle
749    pub fn until_network_almost_idle(
750        id: NavigationId,
751        frame: FrameId,
752        loader_id: Option<LoaderId>,
753    ) -> Self {
754        Self::until_lifecycle(id, frame, loader_id, &[LifecycleEvent::NetworkAlmostIdle])
755    }
756
757    /// (optional) Wait for multiple states, e.g. DOMContentLoaded + networkIdle
758    pub fn until_domcontent_and_network_idle(
759        id: NavigationId,
760        frame: FrameId,
761        loader_id: Option<LoaderId>,
762    ) -> Self {
763        Self::until_lifecycle(
764            id,
765            frame,
766            loader_id,
767            &[
768                LifecycleEvent::DomcontentLoaded,
769                LifecycleEvent::NetworkIdle,
770            ],
771        )
772    }
773
774    /// Checks whether the navigation was completed
775    pub fn is_lifecycle_complete(&self) -> bool {
776        self.expected_lifecycle.is_empty()
777    }
778
779    fn on_frame_navigated_within_document(&mut self, ev: &EventNavigatedWithinDocument) {
780        if self.frame_id == ev.frame_id {
781            self.same_document_navigation = true;
782        }
783    }
784}
785
786/// An identifier for an ongoing navigation
787#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
788pub struct NavigationId(pub usize);
789
790/// Represents a the request for a navigation
791#[derive(Debug)]
792pub struct FrameRequestedNavigation {
793    /// The internal identifier
794    pub id: NavigationId,
795    /// the cdp request that will trigger the navigation
796    pub req: Request,
797    /// The timeout after which the request will be considered timed out
798    pub timeout: Duration,
799}
800
801impl FrameRequestedNavigation {
802    pub fn new(id: NavigationId, req: Request, request_timeout: Duration) -> Self {
803        Self {
804            id,
805            req,
806            timeout: request_timeout,
807        }
808    }
809
810    /// This will set the id of the frame into the `params` `frameId` field.
811    pub fn set_frame_id(&mut self, frame_id: FrameId) {
812        if let Some(params) = self.req.params.as_object_mut() {
813            if let Entry::Vacant(entry) = params.entry("frameId") {
814                entry.insert(serde_json::Value::String(frame_id.into()));
815            }
816        }
817    }
818}
819
820#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
821pub enum LifecycleEvent {
822    #[default]
823    Load,
824    DomcontentLoaded,
825    NetworkIdle,
826    NetworkAlmostIdle,
827}
828
829impl LifecycleEvent {
830    #[inline]
831    pub fn to_method_id(&self) -> MethodId {
832        match self {
833            LifecycleEvent::Load => "load".into(),
834            LifecycleEvent::DomcontentLoaded => "DOMContentLoaded".into(),
835            LifecycleEvent::NetworkIdle => "networkIdle".into(),
836            LifecycleEvent::NetworkAlmostIdle => "networkAlmostIdle".into(),
837        }
838    }
839}
840
841impl AsRef<str> for LifecycleEvent {
842    fn as_ref(&self) -> &str {
843        match self {
844            LifecycleEvent::Load => "load",
845            LifecycleEvent::DomcontentLoaded => "DOMContentLoaded",
846            LifecycleEvent::NetworkIdle => "networkIdle",
847            LifecycleEvent::NetworkAlmostIdle => "networkAlmostIdle",
848        }
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855
856    #[test]
857    fn frame_lifecycle_events_cleared_on_loading_started() {
858        let mut frame = Frame::new(FrameId::new("test"));
859
860        // Simulate a loaded page.
861        frame.lifecycle_events.insert("load".into());
862        frame.lifecycle_events.insert("DOMContentLoaded".into());
863        assert!(frame.is_loaded());
864
865        // Browser fires FrameStartedLoading → on_loading_started clears lifecycle.
866        frame.on_loading_started();
867        assert!(!frame.is_loaded());
868    }
869
870    #[test]
871    fn frame_loading_stopped_inserts_load_events() {
872        let mut frame = Frame::new(FrameId::new("test"));
873        assert!(!frame.is_loaded());
874
875        frame.on_loading_stopped();
876        assert!(frame.is_loaded());
877    }
878}