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