headless_chrome/browser/
context.rs

1use std::sync::Arc;
2
3use anyhow::Result;
4
5use crate::browser::tab::Tab;
6use crate::protocol::cdp::Target::CreateTarget;
7
8/// Equivalent to a new incognito window
9pub struct Context<'a> {
10    id: String,
11    browser: &'a super::Browser,
12}
13
14impl<'a> Context<'a> {
15    pub fn new(browser: &'a super::Browser, context_id: String) -> Self {
16        Self {
17            id: context_id,
18            browser,
19        }
20    }
21
22    /// Opens a new tab in this context. It will not share cookies or a cache with the default
23    /// browsing context or any other contexts created
24    pub fn new_tab(&self) -> Result<Arc<Tab>> {
25        let tab_in_context = CreateTarget {
26            url: "about:blank".to_string(),
27            width: None,
28            height: None,
29            browser_context_id: Some(self.id.clone()),
30            enable_begin_frame_control: None,
31            new_window: None,
32            background: None,
33            for_tab: None,
34        };
35        self.browser.new_tab_with_options(tab_in_context)
36    }
37
38    /// The BrowserContextId associated with this context
39    pub fn get_id(&self) -> &str {
40        &self.id
41    }
42
43    /// Any tabs created in this context
44    pub fn get_tabs(&self) -> Result<Vec<Arc<Tab>>> {
45        let browser_tabs = self.browser.get_tabs().lock().unwrap();
46        let mut tabs = vec![];
47        for tab in browser_tabs.iter() {
48            if let Some(context_id) = tab.get_browser_context_id()? {
49                if context_id == self.id {
50                    tabs.push(Arc::clone(tab));
51                }
52            }
53        }
54        Ok(tabs)
55    }
56}