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 };
20use chromiumoxide_types::{Method, MethodId, Request};
21
22use crate::error::DeadlineExceeded;
23use crate::handler::domworld::DOMWorld;
24use crate::handler::http::HttpRequest;
25use crate::handler::REQUEST_TIMEOUT;
26use crate::{cmd::CommandChain, ArcHttpRequest};
27
28const EVALUATION_SCRIPT_URL: &str = "____chromiumoxide_utility_world___evaluation_script__";
29
30pub fn random_world_name(id: &str) -> String {
39 use rand::Rng;
40 let mut rng = rand::thread_rng();
41 let rand_len = rng.gen_range(6..=12);
42
43 let id_part: String = id
45 .chars()
46 .filter(|c| c.is_ascii_alphanumeric())
47 .take(5)
48 .map(|c| {
49 let c = c.to_ascii_lowercase();
50 if c.is_ascii_alphabetic() {
51 c
52 } else {
53 (b'a' + (c as u8 - b'0') % 26) as char
55 }
56 })
57 .collect();
58
59 let rand_part: String = (0..rand_len)
61 .filter_map(|_| std::char::from_digit(rng.gen_range(0..36), 36))
62 .collect();
63
64 let first = std::char::from_digit(rng.gen_range(10..36), 36).unwrap_or('a');
66
67 format!("{first}{id_part}{rand_part}")
68}
69
70#[derive(Debug)]
72pub struct Frame {
73 parent_frame: Option<FrameId>,
74 id: FrameId,
76 main_world: DOMWorld,
77 secondary_world: DOMWorld,
78 loader_id: Option<LoaderId>,
79 url: Option<String>,
81 http_request: ArcHttpRequest,
83 child_frames: HashSet<FrameId>,
85 name: Option<String>,
86 lifecycle_events: HashSet<MethodId>,
88 isolated_world_name: String,
89}
90
91impl Frame {
92 pub fn new(id: FrameId) -> Self {
93 let isolated_world_name = random_world_name(id.inner());
94
95 Self {
96 parent_frame: None,
97 id,
98 main_world: Default::default(),
99 secondary_world: Default::default(),
100 loader_id: None,
101 url: None,
102 http_request: None,
103 child_frames: Default::default(),
104 name: None,
105 lifecycle_events: Default::default(),
106 isolated_world_name,
107 }
108 }
109
110 pub fn with_parent(id: FrameId, parent: &mut Frame) -> Self {
111 parent.child_frames.insert(id.clone());
112 Self {
113 parent_frame: Some(parent.id.clone()),
114 id,
115 main_world: Default::default(),
116 secondary_world: Default::default(),
117 loader_id: None,
118 url: None,
119 http_request: None,
120 child_frames: Default::default(),
121 name: None,
122 lifecycle_events: Default::default(),
123 isolated_world_name: parent.isolated_world_name.clone(),
124 }
125 }
126
127 pub fn get_isolated_world_name(&self) -> &String {
128 &self.isolated_world_name
129 }
130
131 pub fn parent_id(&self) -> Option<&FrameId> {
132 self.parent_frame.as_ref()
133 }
134
135 pub fn id(&self) -> &FrameId {
136 &self.id
137 }
138
139 pub fn url(&self) -> Option<&str> {
140 self.url.as_deref()
141 }
142
143 pub fn name(&self) -> Option<&str> {
144 self.name.as_deref()
145 }
146
147 pub fn main_world(&self) -> &DOMWorld {
148 &self.main_world
149 }
150
151 pub fn secondary_world(&self) -> &DOMWorld {
152 &self.secondary_world
153 }
154
155 pub fn lifecycle_events(&self) -> &HashSet<MethodId> {
156 &self.lifecycle_events
157 }
158
159 pub fn http_request(&self) -> Option<&Arc<HttpRequest>> {
160 self.http_request.as_ref()
161 }
162
163 fn navigated(&mut self, frame: &CdpFrame) {
164 self.name.clone_from(&frame.name);
165 let url = if let Some(ref fragment) = frame.url_fragment {
166 format!("{}{fragment}", frame.url)
167 } else {
168 frame.url.clone()
169 };
170 self.url = Some(url);
171 }
172
173 fn navigated_within_url(&mut self, url: String) {
174 self.url = Some(url)
175 }
176
177 fn on_loading_stopped(&mut self) {
178 self.lifecycle_events.insert("DOMContentLoaded".into());
179 self.lifecycle_events.insert("load".into());
180 }
181
182 fn on_loading_started(&mut self) {
183 self.lifecycle_events.clear();
184 self.http_request.take();
185 }
186
187 pub fn is_loaded(&self) -> bool {
188 self.lifecycle_events.contains("load")
189 }
190
191 pub fn clear_contexts(&mut self) {
192 self.main_world.take_context();
193 self.secondary_world.take_context();
194 }
195
196 pub fn destroy_context(&mut self, ctx_unique_id: &str) {
197 if self.main_world.execution_context_unique_id() == Some(ctx_unique_id) {
198 self.main_world.take_context();
199 } else if self.secondary_world.execution_context_unique_id() == Some(ctx_unique_id) {
200 self.secondary_world.take_context();
201 }
202 }
203
204 pub fn execution_context(&self) -> Option<ExecutionContextId> {
205 self.main_world.execution_context()
206 }
207
208 pub fn set_request(&mut self, request: HttpRequest) {
209 self.http_request = Some(Arc::new(request))
210 }
211}
212
213#[derive(Debug)]
217pub struct FrameManager {
218 main_frame: Option<FrameId>,
219 frames: HashMap<FrameId, Frame>,
220 context_ids: HashMap<String, FrameId>,
222 isolated_worlds: HashSet<String>,
223 request_timeout: Duration,
226 pending_navigations: VecDeque<(FrameRequestedNavigation, NavigationWatcher)>,
228 navigation: Option<(NavigationWatcher, Instant)>,
230}
231
232impl FrameManager {
233 pub fn new(request_timeout: Duration) -> Self {
234 FrameManager {
235 main_frame: None,
236 frames: Default::default(),
237 context_ids: Default::default(),
238 isolated_worlds: Default::default(),
239 request_timeout,
240 pending_navigations: Default::default(),
241 navigation: None,
242 }
243 }
244
245 pub fn init_commands(timeout: Duration) -> CommandChain {
247 let enable = page::EnableParams::default();
248 let get_tree = page::GetFrameTreeParams::default();
249 let set_lifecycle = page::SetLifecycleEventsEnabledParams::new(true);
250 let mut commands = Vec::with_capacity(3);
254
255 let enable_id = enable.identifier();
256 let get_tree_id = get_tree.identifier();
257 let set_lifecycle_id = set_lifecycle.identifier();
258 if let Ok(value) = serde_json::to_value(enable) {
262 commands.push((enable_id, value));
263 }
264
265 if let Ok(value) = serde_json::to_value(get_tree) {
266 commands.push((get_tree_id, value));
267 }
268
269 if let Ok(value) = serde_json::to_value(set_lifecycle) {
270 commands.push((set_lifecycle_id, value));
271 }
272
273 CommandChain::new(commands, timeout)
282 }
283
284 pub fn main_frame(&self) -> Option<&Frame> {
285 self.main_frame.as_ref().and_then(|id| self.frames.get(id))
286 }
287
288 pub fn main_frame_mut(&mut self) -> Option<&mut Frame> {
289 if let Some(id) = self.main_frame.as_ref() {
290 self.frames.get_mut(id)
291 } else {
292 None
293 }
294 }
295
296 pub fn get_isolated_world_name(&self) -> Option<&String> {
298 self.main_frame
299 .as_ref()
300 .and_then(|id| match self.frames.get(id) {
301 Some(fid) => Some(fid.get_isolated_world_name()),
302 _ => None,
303 })
304 }
305
306 pub fn frames(&self) -> impl Iterator<Item = &Frame> + '_ {
307 self.frames.values()
308 }
309
310 pub fn frame(&self, id: &FrameId) -> Option<&Frame> {
311 self.frames.get(id)
312 }
313
314 fn check_lifecycle(&self, watcher: &NavigationWatcher, frame: &Frame) -> bool {
315 watcher.expected_lifecycle.iter().all(|ev| {
316 frame.lifecycle_events.contains(ev)
317 || (frame.url.is_none() && frame.lifecycle_events.contains("DOMContentLoaded"))
318 }) && frame
319 .child_frames
320 .iter()
321 .filter_map(|f| self.frames.get(f))
322 .all(|f| self.check_lifecycle(watcher, f))
323 }
324
325 fn check_lifecycle_complete(
326 &self,
327 watcher: &NavigationWatcher,
328 frame: &Frame,
329 ) -> Option<NavigationOk> {
330 if !self.check_lifecycle(watcher, frame) {
331 return None;
332 }
333 if frame.loader_id == watcher.loader_id && !watcher.same_document_navigation {
334 return None;
335 }
336 if watcher.same_document_navigation {
337 return Some(NavigationOk::SameDocumentNavigation(watcher.id));
338 }
339 if frame.loader_id != watcher.loader_id {
340 return Some(NavigationOk::NewDocumentNavigation(watcher.id));
341 }
342 None
343 }
344
345 pub fn on_http_request_finished(&mut self, request: HttpRequest) {
347 if let Some(id) = request.frame.as_ref() {
348 if let Some(frame) = self.frames.get_mut(id) {
349 frame.set_request(request);
350 }
351 }
352 }
353
354 pub fn poll(&mut self, now: Instant) -> Option<FrameEvent> {
355 if let Some((watcher, deadline)) = self.navigation.take() {
357 if now > deadline {
358 return Some(FrameEvent::NavigationResult(Err(
360 NavigationError::Timeout {
361 err: DeadlineExceeded::new(now, deadline),
362 id: watcher.id,
363 },
364 )));
365 }
366
367 if let Some(frame) = self.frames.get(&watcher.frame_id) {
368 if let Some(nav) = self.check_lifecycle_complete(&watcher, frame) {
369 return Some(FrameEvent::NavigationResult(Ok(nav)));
372 } else {
373 self.navigation = Some((watcher, deadline));
375 }
376 } else {
377 return Some(FrameEvent::NavigationResult(Err(
378 NavigationError::FrameNotFound {
379 frame: watcher.frame_id,
380 id: watcher.id,
381 },
382 )));
383 }
384 } else if let Some((req, watcher)) = self.pending_navigations.pop_front() {
385 let deadline = Instant::now() + req.timeout;
387 self.navigation = Some((watcher, deadline));
388 return Some(FrameEvent::NavigationRequest(req.id, req.req));
389 }
390 None
391 }
392
393 pub fn goto(&mut self, req: FrameRequestedNavigation) {
395 if let Some(frame_id) = &self.main_frame {
396 self.navigate_frame(frame_id.clone(), req);
397 }
398 }
399
400 pub fn navigate_frame(&mut self, frame_id: FrameId, mut req: FrameRequestedNavigation) {
402 let loader_id = self.frames.get(&frame_id).and_then(|f| f.loader_id.clone());
403 let watcher = NavigationWatcher::until_page_load(req.id, frame_id.clone(), loader_id);
404
405 req.set_frame_id(frame_id);
407
408 self.pending_navigations.push_back((req, watcher))
409 }
410
411 pub fn on_attached_to_target(&mut self, _event: &EventAttachedToTarget) {
413 }
415
416 pub fn on_frame_tree(&mut self, frame_tree: FrameTree) {
417 self.on_frame_attached(
418 frame_tree.frame.id.clone(),
419 frame_tree.frame.parent_id.clone().map(Into::into),
420 );
421 self.on_frame_navigated(&frame_tree.frame);
422 if let Some(children) = frame_tree.child_frames {
423 for child_tree in children {
424 self.on_frame_tree(child_tree);
425 }
426 }
427 }
428
429 pub fn on_frame_attached(&mut self, frame_id: FrameId, parent_frame_id: Option<FrameId>) {
430 if self.frames.contains_key(&frame_id) {
431 return;
432 }
433 if let Some(parent_frame_id) = parent_frame_id {
434 if let Some(parent_frame) = self.frames.get_mut(&parent_frame_id) {
435 let frame = Frame::with_parent(frame_id.clone(), parent_frame);
436 self.frames.insert(frame_id, frame);
437 }
438 }
439 }
440
441 pub fn on_frame_detached(&mut self, event: &EventFrameDetached) {
442 self.remove_frames_recursively(&event.frame_id);
443 }
444
445 pub fn on_frame_navigated(&mut self, frame: &CdpFrame) {
446 if frame.parent_id.is_some() {
447 if let Some((id, mut f)) = self.frames.remove_entry(&frame.id) {
448 for child in f.child_frames.drain() {
449 self.remove_frames_recursively(&child);
450 }
451 f.navigated(frame);
452 self.frames.insert(id, f);
453 }
454 } else {
455 let mut f = if let Some(main) = self.main_frame.take() {
456 if let Some(mut main_frame) = self.frames.remove(&main) {
458 for child in &main_frame.child_frames {
459 self.remove_frames_recursively(child);
460 }
461 main_frame.child_frames.clear();
463 main_frame.id = frame.id.clone();
464 main_frame
465 } else {
466 Frame::new(frame.id.clone())
467 }
468 } else {
469 Frame::new(frame.id.clone())
471 };
472 f.navigated(frame);
473 self.main_frame = Some(f.id.clone());
474 self.frames.insert(f.id.clone(), f);
475 }
476 }
477
478 pub fn on_frame_navigated_within_document(&mut self, event: &EventNavigatedWithinDocument) {
479 if let Some(frame) = self.frames.get_mut(&event.frame_id) {
480 frame.navigated_within_url(event.url.clone());
481 }
482 if let Some((watcher, _)) = self.navigation.as_mut() {
483 watcher.on_frame_navigated_within_document(event);
484 }
485 }
486
487 pub fn on_frame_stopped_loading(&mut self, event: &EventFrameStoppedLoading) {
488 if let Some(frame) = self.frames.get_mut(&event.frame_id) {
489 frame.on_loading_stopped();
490 }
491 }
492
493 pub fn on_frame_started_loading(&mut self, event: &EventFrameStartedLoading) {
495 if let Some(frame) = self.frames.get_mut(&event.frame_id) {
496 frame.on_loading_started();
497 }
498 }
499
500 pub fn on_runtime_binding_called(&mut self, _ev: &EventBindingCalled) {}
502
503 pub fn on_frame_execution_context_created(&mut self, event: &EventExecutionContextCreated) {
505 if let Some(frame_id) = event
506 .context
507 .aux_data
508 .as_ref()
509 .and_then(|v| v["frameId"].as_str())
510 {
511 if let Some(frame) = self.frames.get_mut(frame_id) {
512 if event
513 .context
514 .aux_data
515 .as_ref()
516 .and_then(|v| v["isDefault"].as_bool())
517 .unwrap_or_default()
518 {
519 frame
520 .main_world
521 .set_context(event.context.id, event.context.unique_id.clone());
522 } else if event.context.name == frame.isolated_world_name
523 && frame.secondary_world.execution_context().is_none()
524 {
525 frame
526 .secondary_world
527 .set_context(event.context.id, event.context.unique_id.clone());
528 }
529 self.context_ids
530 .insert(event.context.unique_id.clone(), frame.id.clone());
531 }
532 }
533 if event
534 .context
535 .aux_data
536 .as_ref()
537 .filter(|v| v["type"].as_str() == Some("isolated"))
538 .is_some()
539 {
540 self.isolated_worlds.insert(event.context.name.clone());
541 }
542 }
543
544 pub fn on_frame_execution_context_destroyed(&mut self, event: &EventExecutionContextDestroyed) {
546 if let Some(id) = self.context_ids.remove(&event.execution_context_unique_id) {
547 if let Some(frame) = self.frames.get_mut(&id) {
548 frame.destroy_context(&event.execution_context_unique_id);
549 }
550 }
551 }
552
553 pub fn on_execution_contexts_cleared(&mut self) {
555 for id in self.context_ids.values() {
556 if let Some(frame) = self.frames.get_mut(id) {
557 frame.clear_contexts();
558 }
559 }
560 self.context_ids.clear()
561 }
562
563 pub fn on_page_lifecycle_event(&mut self, event: &EventLifecycleEvent) {
565 if let Some(frame) = self.frames.get_mut(&event.frame_id) {
566 if event.name == "init" {
567 frame.loader_id = Some(event.loader_id.clone());
568 frame.lifecycle_events.clear();
569 }
570 frame.lifecycle_events.insert(event.name.clone().into());
571 }
572 }
573
574 fn remove_frames_recursively(&mut self, id: &FrameId) -> Option<Frame> {
576 if let Some(mut frame) = self.frames.remove(id) {
577 for child in &frame.child_frames {
578 self.remove_frames_recursively(child);
579 }
580 if let Some(parent_id) = frame.parent_frame.take() {
581 if let Some(parent) = self.frames.get_mut(&parent_id) {
582 parent.child_frames.remove(&frame.id);
583 }
584 }
585 Some(frame)
586 } else {
587 None
588 }
589 }
590
591 pub fn ensure_isolated_world(&mut self, world_name: &str) -> Option<CommandChain> {
592 if self.isolated_worlds.contains(world_name) {
593 return None;
594 }
595
596 self.isolated_worlds.insert(world_name.to_string());
597
598 let cmd = AddScriptToEvaluateOnNewDocumentParams::builder()
599 .source(format!("//# sourceURL={EVALUATION_SCRIPT_URL}"))
600 .world_name(world_name)
601 .build()
602 .unwrap();
603
604 let mut cmds = Vec::with_capacity(self.frames.len() + 1);
605
606 cmds.push((cmd.identifier(), serde_json::to_value(cmd).unwrap()));
607
608 let cm = self.frames.keys().filter_map(|id| {
609 if let Ok(cmd) = CreateIsolatedWorldParams::builder()
610 .frame_id(id.clone())
611 .grant_univeral_access(true)
612 .world_name(world_name)
613 .build()
614 {
615 let cm = (
616 cmd.identifier(),
617 serde_json::to_value(cmd).unwrap_or_default(),
618 );
619
620 Some(cm)
621 } else {
622 None
623 }
624 });
625
626 cmds.extend(cm);
627
628 Some(CommandChain::new(cmds, self.request_timeout))
629 }
630}
631
632#[derive(Debug)]
633pub enum FrameEvent {
634 NavigationResult(Result<NavigationOk, NavigationError>),
636 NavigationRequest(NavigationId, Request),
638 }
641
642#[derive(Debug)]
643pub enum NavigationError {
644 Timeout {
645 id: NavigationId,
646 err: DeadlineExceeded,
647 },
648 FrameNotFound {
649 id: NavigationId,
650 frame: FrameId,
651 },
652}
653
654impl NavigationError {
655 pub fn navigation_id(&self) -> &NavigationId {
656 match self {
657 NavigationError::Timeout { id, .. } => id,
658 NavigationError::FrameNotFound { id, .. } => id,
659 }
660 }
661}
662
663#[derive(Debug, Clone, Eq, PartialEq)]
664pub enum NavigationOk {
665 SameDocumentNavigation(NavigationId),
666 NewDocumentNavigation(NavigationId),
667}
668
669impl NavigationOk {
670 pub fn navigation_id(&self) -> &NavigationId {
671 match self {
672 NavigationOk::SameDocumentNavigation(id) => id,
673 NavigationOk::NewDocumentNavigation(id) => id,
674 }
675 }
676}
677
678#[derive(Debug)]
680pub struct NavigationWatcher {
681 id: NavigationId,
682 expected_lifecycle: HashSet<MethodId>,
683 frame_id: FrameId,
684 loader_id: Option<LoaderId>,
685 same_document_navigation: bool,
690}
691
692impl NavigationWatcher {
693 pub fn until_page_load(id: NavigationId, frame: FrameId, loader_id: Option<LoaderId>) -> Self {
694 Self {
695 id,
696 expected_lifecycle: std::iter::once("load".into()).collect(),
697 loader_id,
698 frame_id: frame,
699 same_document_navigation: false,
700 }
701 }
702
703 pub fn is_lifecycle_complete(&self) -> bool {
705 self.expected_lifecycle.is_empty()
706 }
707
708 fn on_frame_navigated_within_document(&mut self, ev: &EventNavigatedWithinDocument) {
709 if self.frame_id == ev.frame_id {
710 self.same_document_navigation = true;
711 }
712 }
713}
714
715#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
717pub struct NavigationId(pub usize);
718
719#[derive(Debug)]
721pub struct FrameRequestedNavigation {
722 pub id: NavigationId,
724 pub req: Request,
726 pub timeout: Duration,
728}
729
730impl FrameRequestedNavigation {
731 pub fn new(id: NavigationId, req: Request) -> Self {
732 Self {
733 id,
734 req,
735 timeout: Duration::from_millis(REQUEST_TIMEOUT),
736 }
737 }
738
739 pub fn set_frame_id(&mut self, frame_id: FrameId) {
741 if let Some(params) = self.req.params.as_object_mut() {
742 if let Entry::Vacant(entry) = params.entry("frameId") {
743 entry.insert(serde_json::Value::String(frame_id.into()));
744 }
745 }
746 }
747}
748
749#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
750pub enum LifecycleEvent {
751 #[default]
752 Load,
753 DomcontentLoaded,
754 NetworkIdle,
755 NetworkAlmostIdle,
756}
757
758impl AsRef<str> for LifecycleEvent {
759 fn as_ref(&self) -> &str {
760 match self {
761 LifecycleEvent::Load => "load",
762 LifecycleEvent::DomcontentLoaded => "DOMContentLoaded",
763 LifecycleEvent::NetworkIdle => "networkIdle",
764 LifecycleEvent::NetworkAlmostIdle => "networkAlmostIdle",
765 }
766 }
767}