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 r = upgrade(&inner)?.launch(args).await?;
105 Ok(Browser::new(r))
106 }
107
108 fn new(inner: Weak<Impl>) -> Self {
109 Launcher {
110 inner,
111 args: LaunchArgs::default()
112 }
113 }
114
115 setter! {
116 /// Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
117 /// resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox
118 /// or WebKit, use at your own risk.
119 executable: Option<&'a Path>,
120 /// Additional arguments to pass to the browser instance. The list of Chromium flags can be found
121 /// [here](http://peter.sh/experiments/chromium-command-line-switches/).
122 args: Option<&'b [String]>,
123 /// If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;
124 /// use with care. Defaults to `false`.
125 ignore_all_default_args: Option<bool>,
126 /// Close the browser process on Ctrl-C. Defaults to `true`.
127 handle_sigint: Option<bool>,
128 /// Close the browser process on SIGTERM. Defaults to `true`.
129 handle_sigterm: Option<bool>,
130 /// Close the browser process on SIGHUP. Defaults to `true`.
131 handle_sighup: Option<bool>,
132 /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
133 /// disable timeout.
134 timeout: Option<f64>,
135 /// **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless`
136 /// option will be set `false`.
137 devtools: Option<bool>,
138 /// Network proxy settings.
139 proxy: Option<ProxySettings>,
140 /// If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is
141 /// deleted when browser is closed.
142 downloads: Option<&'c Path>,
143 /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
144 slowmo: Option<f64>,
145 /// Specify environment variables that will be visible to the browser. Defaults to `process.env`.
146 env: Option<Map<String, Value>>,
147 /// Whether to run browser in headless mode. More details for
148 /// [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
149 /// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
150 /// `devtools` option is `true`.
151 headless: Option<bool>,
152 /// Enable Chromium sandboxing. Defaults to `false`.
153 chromium_sandbox: Option<bool>,
154 /// Firefox user preferences. Learn more about the Firefox user preferences at
155 /// [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
156 firefox_user_prefs: Option<Map<String, Value>>,
157 channel: Option<BrowserChannel>
158 }
159 //#[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`."]
160 // ignore_default_args: Option<NotImplementedYet>,
161 //#[doc = "Logger sink for Playwright logging."]
162 // logger: Option<Logger>,
163}
164
165/// [`BrowserType::persistent_context_launcher`]
166///
167/// Has launch args and context args
168pub struct PersistentContextLauncher<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k> {
169 inner: Weak<Impl>,
170 args: LaunchPersistentContextArgs<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
171}
172
173impl<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
174 PersistentContextLauncher<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k>
175{
176 pub async fn launch(self) -> Result<BrowserContext, Arc<Error>> {
177 let Self { inner, args } = self;
178 let r = upgrade(&inner)?.launch_persistent_context(args).await?;
179 Ok(BrowserContext::new(r))
180 }
181
182 fn new(inner: Weak<Impl>, user_data_dir: &'a Path) -> Self {
183 Self {
184 inner,
185 args: LaunchPersistentContextArgs::new(user_data_dir)
186 }
187 }
188
189 pub fn set_device(self, device: &'e DeviceDescriptor) -> Self {
190 DeviceDescriptor::set_persistent_context(device, self)
191 }
192
193 setter! {
194 /// Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
195 /// resolved relative to the current working directory. **BEWARE**: Playwright is only guaranteed to work with the bundled
196 /// Chromium, Firefox or WebKit, use at your own risk.
197 executable: Option<&'b Path>,
198 /// Additional arguments to pass to the browser instance. The list of Chromium flags can be found
199 /// [here](http://peter.sh/experiments/chromium-command-line-switches/).
200 args: Option<&'c [String]>,
201 /// If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;
202 /// use with care. Defaults to `false`.
203 ignore_all_default_args: Option<bool>,
204 /// Close the browser process on SIGHUP. Defaults to `true`.
205 handle_sighup: Option<bool>,
206 /// Close the browser process on Ctrl-C. Defaults to `true`.
207 handle_sigint: Option<bool>,
208 /// Close the browser process on SIGTERM. Defaults to `true`.
209 handle_sigterm: Option<bool>,
210 /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
211 /// disable timeout.
212 timeout: Option<f64>,
213 /// Specify environment variables that will be visible to the browser. Defaults to `process.env`.
214 env: Option<Map<String, Value>>,
215 /// Whether to run browser in headless mode. More details for
216 /// [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
217 /// [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
218 /// `devtools` option is `true`.
219 headless: Option<bool>,
220 /// **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless`
221 /// option will be set `false`.
222 devtools: Option<bool>,
223 /// Network proxy settings.
224 proxy: Option<ProxySettings>,
225 /// If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is
226 /// deleted when browser is closed.
227 downloads: Option<&'d Path>,
228 /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
229 /// Defaults to 0.
230 slowmo: Option<f64>,
231 /// Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
232 viewport: Option<Option<Viewport>>,
233 /// Does not enforce fixed viewport, allows resizing window in the headed mode.
234 no_viewport: Option<bool>,
235 /// Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport`
236 /// is set.
237 screen: Option<Viewport>,
238 /// Whether to ignore HTTPS errors during navigation. Defaults to `false`.
239 ignore_https_errors: Option<bool>,
240 /// Whether or not to enable JavaScript in the context. Defaults to `true`.
241 js_enabled: Option<bool>,
242 /// Toggles bypassing page's Content-Security-Policy.
243 bypass_csp: Option<bool>,
244 /// Specific user agent to use in this context.
245 user_agent: Option<&'e str>,
246 /// Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language`
247 /// request header value as well as number and date formatting rules.
248 locale: Option<&'f str>,
249 /// Changes the timezone of the context. See
250 /// [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
251 /// for a list of supported timezone IDs.
252 timezone_id: Option<&'g str>,
253 geolocation: Option<Geolocation>,
254 /// A list of permissions to grant to all pages in this context. See [`method: BrowserContext.grantPermissions`] for more
255 /// details.
256 permissions: Option<&'h [String]>,
257 /// An object containing additional HTTP headers to be sent with every request. All header values must be strings.
258 extra_http_headers: Option<HashMap<String, String>>,
259 /// Whether to emulate network being offline. Defaults to `false`.
260 offline: Option<bool>,
261 /// Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
262 http_credentials: Option<&'i HttpCredentials>,
263 /// Specify device scale factor (can be thought of as dpr). Defaults to `1`.
264 device_scale_factor: Option<f64>,
265 /// Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported
266 /// in Firefox.
267 is_mobile: Option<bool>,
268 /// Specifies if viewport supports touch events. Defaults to false.
269 has_touch: Option<bool>,
270 /// Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
271 /// [`method: Page.emulateMedia`] for more details. Defaults to `'light'`.
272 color_scheme: Option<ColorScheme>,
273 /// Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
274 accept_downloads: Option<bool>,
275 /// Enable Chromium sandboxing. Defaults to `true`.
276 chromium_sandbox: Option<bool>,
277 /// Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
278 /// sure to await [`method: BrowserContext.close`] for videos to be saved.
279 record_video: Option<RecordVideo<'j>>,
280 /// Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not
281 /// specified, the HAR is not recorded. Make sure to await [`method: BrowserContext.close`] for the HAR to be saved.
282 record_har: Option<RecordHar<'k>>,
283
284 channel: Option<BrowserChannel>
285 }
286 //#[doc = "If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. Dangerous option;\nuse with care."]
287 // ignore_default_args: Option<Vec<String>>,
288 //#[doc = "Logger sink for Playwright logging."] logger: Option<Logger>,
289 //#[doc = "Optional setting to control whether to omit request content from the HAR. Defaults to `false`."]
290 // record_har_omit_content: Option<bool>,
291 //#[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."]
292 // record_har_path: Option<path>,
293 //#[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."]
294 // record_video_dir: Option<path>,
295 //#[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."]
296 // record_video_size: Option<NotImplementedYet>,
297 //#[doc = "**DEPRECATED** Use `recordVideo` instead."] video_size: Option<NotImplementedYet>,
298 //#[doc = "**DEPRECATED** Use `recordVideo` instead."] videos_path: Option<path>,
299}
300
301pub struct ConnectOverCdpBuilder<'a> {
302 inner: Weak<Impl>,
303 args: ConnectOverCdpArgs<'a>
304}
305
306impl<'a> ConnectOverCdpBuilder<'a> {
307 pub async fn connect_over_cdp(self) -> ArcResult<Browser> {
308 let Self { inner, args } = self;
309 let r = upgrade(&inner)?.connect_over_cdp(args).await?;
310 Ok(Browser::new(r))
311 }
312
313 fn new(inner: Weak<Impl>, endpoint_url: &'a str) -> Self {
314 Self {
315 inner,
316 args: ConnectOverCdpArgs::new(endpoint_url)
317 }
318 }
319
320 setter! {
321 /// Additional HTTP headers to be sent with web socket connect request. Optional.
322 headers: Option<HashMap<String, String>>,
323 /// Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to
324 /// disable timeout.
325 timeout: Option<f64>,
326 /// Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
327 /// Defaults to 0.
328 slowmo: Option<f64>
329 }
330}