playwright/api/browser.rs
1pub use crate::imp::browser_type::{RecordHar, RecordVideo};
2use crate::{
3 api::BrowserContext,
4 imp::{
5 self,
6 browser::NewContextArgs,
7 core::*,
8 playwright::DeviceDescriptor,
9 prelude::*,
10 utils::{ColorScheme, Geolocation, HttpCredentials, ProxySettings, StorageState, Viewport}
11 },
12 Error
13};
14
15#[derive(Debug)]
16pub struct Browser {
17 inner: Weak<imp::browser::Browser>
18}
19
20impl PartialEq for Browser {
21 fn eq(&self, other: &Self) -> bool {
22 let a = self.inner.upgrade();
23 let b = other.inner.upgrade();
24 a.and_then(|a| b.map(|b| (a, b)))
25 .map(|(a, b)| a.guid() == b.guid())
26 .unwrap_or_default()
27 }
28}
29
30impl Browser {
31 pub(crate) fn new(inner: Weak<imp::browser::Browser>) -> Self { Self { inner } }
32
33 /// Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
34 ///
35 /// ```js
36 /// const browser = await pw.webkit.launch();
37 /// console.log(browser.contexts().length); // prints `0`
38 ///
39 /// const context = await browser.newContext();
40 /// console.log(browser.contexts().length); // prints `1`
41 /// ```
42 pub fn contexts(&self) -> Result<Vec<BrowserContext>, Error> {
43 Ok(upgrade(&self.inner)?
44 .contexts()
45 .iter()
46 .cloned()
47 .map(BrowserContext::new)
48 .collect())
49 }
50
51 /// Returns the browser version.
52 pub fn version(&self) -> Result<String, Error> {
53 Ok(upgrade(&self.inner)?.version().to_owned())
54 }
55
56 pub fn exists(&self) -> bool { self.inner.upgrade().is_some() }
57
58 /// new_context [`BrowserContext`]
59 /// Creates a new browser context. It won't share cookies/cache with other browser contexts.
60 pub fn context_builder(&self) -> ContextBuilder<'_, '_, '_, '_, '_, '_, '_> {
61 ContextBuilder::new(self.inner.clone())
62 }
63
64 /// All temporary browsers will be closed when the connection is terminated, but
65 /// it needs to be called explicitly to close it at any given time.
66 pub async fn close(&self) -> Result<(), Arc<Error>> {
67 let inner = match self.inner.upgrade() {
68 None => return Ok(()),
69 Some(inner) => inner
70 };
71 inner.close().await
72 }
73
74 // new_browser_cdp_session
75 // start_tracing
76 // stop_tracing
77}
78
79// TODO: async drop
80
81/// [`Browser::context_builder`]
82pub struct ContextBuilder<'e, 'f, 'g, 'h, 'i, 'j, 'k> {
83 inner: Weak<imp::browser::Browser>,
84 args: NewContextArgs<'e, 'f, 'g, 'h, 'i, 'j, 'k>
85}
86
87impl<'e, 'f, 'g, 'h, 'i, 'j, 'k> ContextBuilder<'e, 'f, 'g, 'h, 'i, 'j, 'k> {
88 pub async fn build(self) -> Result<BrowserContext, Arc<Error>> {
89 let Self { inner, args } = self;
90 let r = upgrade(&inner)?.new_context(args).await?;
91 Ok(BrowserContext::new(r))
92 }
93
94 fn new(inner: Weak<imp::browser::Browser>) -> Self {
95 Self {
96 inner,
97 args: NewContextArgs::default()
98 }
99 }
100
101 pub fn set_device(self, device: &'e DeviceDescriptor) -> Self {
102 DeviceDescriptor::set_context(device, self)
103 }
104
105 setter! {
106 /// Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
107 accept_downloads: Option<bool>,
108 /// Toggles bypassing page's Content-Security-Policy.
109 bypass_csp: Option<bool>,
110 /// Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
111 /// [`method: Page.emulateMedia`] for more details. Defaults to `'light'`.
112 color_scheme: Option<ColorScheme>,
113 /// Specify device scale factor (can be thought of as dpr). Defaults to `1`.
114 device_scale_factor: Option<f64>,
115 /// An object containing additional HTTP headers to be sent with every request. All header values must be strings.
116 extra_http_headers: Option<HashMap<String, String>>,
117 geolocation: Option<Geolocation>,
118 has_touch: Option<bool>,
119 /// Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
120 http_credentials: Option<&'i HttpCredentials>,
121 /// Whether to ignore HTTPS errors during navigation. Defaults to `false`.
122 ignore_https_errors: Option<bool>,
123 /// Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported
124 /// in Firefox.
125 is_mobile: Option<bool>,
126 /// Whether or not to enable JavaScript in the context. Defaults to `true`.
127 js_enabled: Option<bool>,
128 /// Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language`
129 /// request header value as well as number and date formatting rules.
130 locale: Option<&'f str>,
131 /// Does not enforce fixed viewport, allows resizing window in the headed mode.
132 no_viewport: Option<bool>,
133 /// Whether to emulate network being offline. Defaults to `false`.
134 offline: Option<bool>,
135 /// A list of permissions to grant to all pages in this context. See [BrowserContext::grant_permissions] for more details.
136 permissions: Option<&'h [String]>,
137 /// Network proxy settings to use with this context. Note that browser needs to be launched with the global proxy for this
138 /// option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example
139 /// `launch({ proxy: { server: 'per-context' } })`.
140 proxy: Option<ProxySettings>,
141 /// Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not
142 /// specified, the HAR is not recorded. Make sure to await [`method: BrowserContext.close`] for the HAR to be saved.
143 record_har: Option<RecordHar<'k>>,
144 /// Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
145 /// sure to await [`method: BrowserContext.close`] for videos to be saved.
146 record_video: Option<RecordVideo<'j>>,
147 /// Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport`
148 /// is set.
149 screen: Option<Viewport>,
150 /// Populates context with given storage state. This option can be used to initialize context with logged-in information
151 /// obtained via [`method: BrowserContext.storageState`]. Either a path to the file with saved storage, or an object with
152 /// the following fields:
153 storage_state: Option<StorageState>,
154 /// Changes the timezone of the context. See
155 /// [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
156 /// for a list of supported timezone IDs.
157 timezone_id: Option<&'g str>,
158 /// Specific user agent to use in this context.
159 user_agent: Option<&'e str>,
160 /// Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
161 viewport: Option<Option<Viewport>>
162 }
163 ///// Logger sink for Playwright logging.
164 // logger: Option<Logger>,
165}