playwright/api/
browser_type.rs

1pub use crate::imp::browser_type::{RecordHar, RecordVideo};
2use crate::{
3    api::{browser::Browser, browser_context::BrowserContext, playwright::DeviceDescriptor},
4    imp::{
5        browser_type::{
6            BrowserType as Impl, ConnectOverCdpArgs, LaunchArgs, LaunchPersistentContextArgs
7        },
8        core::*,
9        prelude::*,
10        utils::{
11            BrowserChannel, ColorScheme, Geolocation, HttpCredentials, ProxySettings, Viewport
12        }
13    },
14    Error
15};
16
17#[derive(Debug, Clone)]
18pub struct BrowserType {
19    inner: Weak<Impl>
20}
21
22impl BrowserType {
23    pub(crate) fn new(inner: Weak<Impl>) -> Self { Self { inner } }
24
25    /// Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
26    /// # Errors
27    /// Returns error only if this function is called after object is disposed.
28    pub fn name(&self) -> Result<String, Error> { Ok(upgrade(&self.inner)?.name().into()) }
29
30    /// A path where Playwright expects to find a bundled browser executable.
31    /// # Errors
32    /// Returns error only if this function is called after object is disposed.
33    pub fn executable(&self) -> Result<PathBuf, Error> {
34        Ok(upgrade(&self.inner)?.executable().into())
35    }
36
37    /// launch [`Browser`]
38    /// Returns the browser instance.
39    ///
40    /// You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
41    ///
42    /// ```js
43    /// const browser = await chromium.launch({  // Or 'firefox' or 'webkit'.
44    ///  ignoreDefaultArgs: ['--mute-audio']
45    /// });
46    /// ```
47    ///
48    /// > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works
49    /// best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use
50    /// `executablePath` option with extreme caution.
51    /// >
52    /// > If Google Chrome (rather than Chromium) is preferred, a
53    /// [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
54    /// [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
55    /// >
56    /// > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for
57    /// video playback. See
58    /// [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for other
59    /// differences between Chromium and Chrome.
60    /// [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
61    /// describes some differences for Linux users.
62    pub fn launcher(&self) -> Launcher<'_, '_, '_> { Launcher::new(self.inner.clone()) }
63
64    /// launch_persistent_context [`BrowserContext`]
65    /// Returns the persistent browser context instance.
66    ///
67    /// Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
68    /// context will automatically close the browser.
69    /// user_data_dir: Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for
70    /// [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
71    /// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile). Note that Chromium's user
72    /// data directory is the **parent** directory of the "Profile Path" seen at `chrome://version`.
73    pub fn persistent_context_launcher<'a>(
74        &self,
75        user_data_dir: &'a Path
76    ) -> PersistentContextLauncher<'a, '_, '_, '_, '_, '_, '_, '_, '_, '_, '_> {
77        PersistentContextLauncher::new(self.inner.clone(), user_data_dir)
78    }
79
80    /// This methods attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
81    ///
82    /// The default browser context is accessible via [`method: Browser.contexts`].
83    ///
84    /// > NOTE: Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
85    /// A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
86    /// `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
87    pub fn connect_over_cdp_builder<'a>(&self, endpoint_url: &'a str) -> ConnectOverCdpBuilder<'a> {
88        ConnectOverCdpBuilder::new(self.inner.clone(), endpoint_url)
89    }
90
91    // connect
92    // launch_server
93}
94
95/// [`BrowserType::launcher`]
96pub struct Launcher<'a, 'b, 'c> {
97    inner: Weak<Impl>,
98    args: LaunchArgs<'a, 'b, 'c>
99}
100
101impl<'a, 'b, 'c> Launcher<'a, 'b, 'c> {
102    pub async fn launch(self) -> Result<Browser, Arc<Error>> {
103        let Self { inner, args } = self;
104        let inner_arc = upgrade(&inner)?;
105        let r = inner_arc.launch(args).await?;
106        Ok(Browser::new(r))
107    }
108
109    fn new(inner: Weak<Impl>) -> Self {
110        let mut args = LaunchArgs::default();
111        // Playwright 1.50+ requires an explicit timeout value
112        args.timeout = Some(30000.0);
113        Launcher {
114            inner,
115            args
116        }
117    }
118
119    setter! {
120        /// Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
121        /// resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox
122        /// or WebKit, use at your own risk.
123        executable: Option<&'a Path>,
124        /// Additional arguments to pass to the browser instance. The list of Chromium flags can be found
125        /// [here](http://peter.sh/experiments/chromium-command-line-switches/).
126        args: Option<&'b [String]>,
127        /// If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;
128        /// use with care. Defaults to `false`.
129        ignore_all_default_args: Option<bool>,
130        /// Close the browser process on Ctrl-C. Defaults to `true`.
131        handle_sigint: Option<bool>,
132        /// Close the browser process on SIGTERM. Defaults to `true`.
133        handle_sigterm: Option<bool>,
134        /// Close the browser process on SIGHUP. Defaults to `true`.
135        handle_sighup: Option<bool>,
136        /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
137        /// disable timeout.
138        timeout: Option<f64>,
139        /// **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless`
140        /// option will be set `false`.
141        devtools: Option<bool>,
142        /// Network proxy settings.
143        proxy: Option<ProxySettings>,
144        /// If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is
145        /// deleted when browser is closed.
146        downloads: Option<&'c Path>,
147        /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
148        slowmo: Option<f64>,
149        /// Specify environment variables that will be visible to the browser. Defaults to `process.env`.
150        env: Option<Map<String, Value>>,
151        /// Whether to run browser in headless mode. More details for
152        /// [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
153        /// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
154        /// `devtools` option is `true`.
155        headless: Option<bool>,
156        /// Enable Chromium sandboxing. Defaults to `false`.
157        chromium_sandbox: Option<bool>,
158        /// Firefox user preferences. Learn more about the Firefox user preferences at
159        /// [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
160        firefox_user_prefs: Option<Map<String, Value>>,
161        channel: Option<BrowserChannel>
162    }
163    //#[doc = "If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is\ngiven, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`."]
164    // ignore_default_args: Option<NotImplementedYet>,
165    //#[doc = "Logger sink for Playwright logging."]
166    // logger: Option<Logger>,
167}
168
169/// [`BrowserType::persistent_context_launcher`]
170///
171/// Has launch args and context args
172pub struct PersistentContextLauncher<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k> {
173    inner: Weak<Impl>,
174    args: LaunchPersistentContextArgs<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
175}
176
177impl<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
178    PersistentContextLauncher<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
179{
180    pub async fn launch(self) -> Result<BrowserContext, Arc<Error>> {
181        let Self { inner, args } = self;
182        let r = upgrade(&inner)?.launch_persistent_context(args).await?;
183        Ok(BrowserContext::new(r))
184    }
185
186    fn new(inner: Weak<Impl>, user_data_dir: &'a Path) -> Self {
187        Self {
188            inner,
189            args: LaunchPersistentContextArgs::new(user_data_dir)
190        }
191    }
192
193    pub fn set_device(self, device: &'e DeviceDescriptor) -> Self {
194        DeviceDescriptor::set_persistent_context(device, self)
195    }
196
197    setter! {
198        /// Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
199        /// resolved relative to the current working directory. **BEWARE**: Playwright is only guaranteed to work with the bundled
200        /// Chromium, Firefox or WebKit, use at your own risk.
201        executable: Option<&'b Path>,
202        /// Additional arguments to pass to the browser instance. The list of Chromium flags can be found
203        /// [here](http://peter.sh/experiments/chromium-command-line-switches/).
204        args: Option<&'c [String]>,
205        /// If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;
206        /// use with care. Defaults to `false`.
207        ignore_all_default_args: Option<bool>,
208        /// Close the browser process on SIGHUP. Defaults to `true`.
209        handle_sighup: Option<bool>,
210        /// Close the browser process on Ctrl-C. Defaults to `true`.
211        handle_sigint: Option<bool>,
212        /// Close the browser process on SIGTERM. Defaults to `true`.
213        handle_sigterm: Option<bool>,
214        /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
215        /// disable timeout.
216        timeout: Option<f64>,
217        /// Specify environment variables that will be visible to the browser. Defaults to `process.env`.
218        env: Option<Map<String, Value>>,
219        /// Whether to run browser in headless mode. More details for
220        /// [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
221        /// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
222        /// `devtools` option is `true`.
223        headless: Option<bool>,
224        /// **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless`
225        /// option will be set `false`.
226        devtools: Option<bool>,
227        /// Network proxy settings.
228        proxy: Option<ProxySettings>,
229        /// If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is
230        /// deleted when browser is closed.
231        downloads: Option<&'d Path>,
232        /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
233        /// Defaults to 0.
234        slowmo: Option<f64>,
235        /// Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
236        viewport: Option<Option<Viewport>>,
237        /// Does not enforce fixed viewport, allows resizing window in the headed mode.
238        no_viewport: Option<bool>,
239        /// Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport`
240        /// is set.
241        screen: Option<Viewport>,
242        /// Whether to ignore HTTPS errors during navigation. Defaults to `false`.
243        ignore_https_errors: Option<bool>,
244        /// Whether or not to enable JavaScript in the context. Defaults to `true`.
245        js_enabled: Option<bool>,
246        /// Toggles bypassing page's Content-Security-Policy.
247        bypass_csp: Option<bool>,
248        /// Specific user agent to use in this context.
249        user_agent: Option<&'e str>,
250        /// Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language`
251        /// request header value as well as number and date formatting rules.
252        locale: Option<&'f str>,
253        /// Changes the timezone of the context. See
254        /// [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
255        /// for a list of supported timezone IDs.
256        timezone_id: Option<&'g str>,
257        geolocation: Option<Geolocation>,
258        /// A list of permissions to grant to all pages in this context. See [`method: BrowserContext.grantPermissions`] for more
259        /// details.
260        permissions: Option<&'h [String]>,
261        /// An object containing additional HTTP headers to be sent with every request. All header values must be strings.
262        extra_http_headers: Option<HashMap<String, String>>,
263        /// Whether to emulate network being offline. Defaults to `false`.
264        offline: Option<bool>,
265        /// Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
266        http_credentials: Option<&'i HttpCredentials>,
267        /// Specify device scale factor (can be thought of as dpr). Defaults to `1`.
268        device_scale_factor: Option<f64>,
269        /// Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported
270        /// in Firefox.
271        is_mobile: Option<bool>,
272        /// Specifies if viewport supports touch events. Defaults to false.
273        has_touch: Option<bool>,
274        /// Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
275        /// [`method: Page.emulateMedia`] for more details. Defaults to `'light'`.
276        color_scheme: Option<ColorScheme>,
277        /// Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
278        accept_downloads: Option<bool>,
279        /// Enable Chromium sandboxing. Defaults to `true`.
280        chromium_sandbox: Option<bool>,
281        /// Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
282        /// sure to await [`method: BrowserContext.close`] for videos to be saved.
283        record_video: Option<RecordVideo<'j>>,
284        /// Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not
285        /// specified, the HAR is not recorded. Make sure to await [`method: BrowserContext.close`] for the HAR to be saved.
286        record_har: Option<RecordHar<'k>>,
287
288        channel: Option<BrowserChannel>
289    }
290    //#[doc = "If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;\nuse with care."]
291    // ignore_default_args: Option<Vec<String>>,
292    //#[doc = "Logger sink for Playwright logging."] logger: Option<Logger>,
293    //#[doc = "Optional setting to control whether to omit request content from the HAR. Defaults to `false`."]
294    // record_har_omit_content: Option<bool>,
295    //#[doc = "Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into the specified HAR file on the\nfilesystem. If not specified, the HAR is not recorded. Make sure to call [`method: BrowserContext.close`] for the HAR to\nbe saved."]
296    // record_har_path: Option<path>,
297    //#[doc = "Enables video recording for all pages into the specified directory. If not specified videos are not recorded. Make sure\nto call [`method: BrowserContext.close`] for videos to be saved."]
298    // record_video_dir: Option<path>,
299    //#[doc = "Dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to fit into\n800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of each page will\nbe scaled down if necessary to fit the specified size."]
300    // record_video_size: Option<NotImplementedYet>,
301    //#[doc = "**DEPRECATED** Use `recordVideo` instead."] video_size: Option<NotImplementedYet>,
302    //#[doc = "**DEPRECATED** Use `recordVideo` instead."] videos_path: Option<path>,
303}
304
305pub struct ConnectOverCdpBuilder<'a> {
306    inner: Weak<Impl>,
307    args: ConnectOverCdpArgs<'a>
308}
309
310impl<'a> ConnectOverCdpBuilder<'a> {
311    pub async fn connect_over_cdp(self) -> ArcResult<Browser> {
312        let Self { inner, args } = self;
313        let r = upgrade(&inner)?.connect_over_cdp(args).await?;
314        Ok(Browser::new(r))
315    }
316
317    fn new(inner: Weak<Impl>, endpoint_url: &'a str) -> Self {
318        Self {
319            inner,
320            args: ConnectOverCdpArgs::new(endpoint_url)
321        }
322    }
323
324    setter! {
325        /// Additional HTTP headers to be sent with web socket connect request. Optional.
326        headers: Option<HashMap<String, String>>,
327        /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
328        /// disable timeout.
329        timeout: Option<f64>,
330        /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
331        /// Defaults to 0.
332        slowmo: Option<f64>
333    }
334}