How to use setVideoRecordingOptions method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

BrowserHandler.js

Source: BrowserHandler.js Github

copy
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5"use strict";
6
7const {AddonManager} = ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
8const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
9const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");
10const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');
11const {PageHandler} = ChromeUtils.import("chrome://juggler/content/protocol/PageHandler.js");
12const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
13
14const helper = new Helper();
15
16class BrowserHandler {
17  constructor(session, dispatcher, targetRegistry, onclose) {
18    this._session = session;
19    this._dispatcher = dispatcher;
20    this._targetRegistry = targetRegistry;
21    this._enabled = false;
22    this._attachToDefaultContext = false;
23    this._eventListeners = [];
24    this._createdBrowserContextIds = new Set();
25    this._attachedSessions = new Map();
26    this._onclose = onclose;
27  }
28
29  async ['Browser.enable']({attachToDefaultContext}) {
30    if (this._enabled)
31      return;
32    this._enabled = true;
33    this._attachToDefaultContext = attachToDefaultContext;
34
35    this._eventListeners = [
36      helper.on(this._targetRegistry, TargetRegistry.Events.TargetCreated, this._onTargetCreated.bind(this)),
37      helper.on(this._targetRegistry, TargetRegistry.Events.TargetDestroyed, this._onTargetDestroyed.bind(this)),
38      helper.on(this._targetRegistry, TargetRegistry.Events.DownloadCreated, this._onDownloadCreated.bind(this)),
39      helper.on(this._targetRegistry, TargetRegistry.Events.DownloadFinished, this._onDownloadFinished.bind(this)),
40      helper.on(this._targetRegistry, TargetRegistry.Events.ScreencastStopped, sessionId => {
41        this._session.emitEvent('Browser.videoRecordingFinished', {screencastId: '' + sessionId});
42      })
43    ];
44
45    for (const target of this._targetRegistry.targets())
46      this._onTargetCreated(target);
47
48    // Wait to complete initialization of addon manager and search
49    // service before returning from this method. Failing to do so will result
50    // in a broken shutdown sequence and multiple errors in browser STDERR log.
51    //
52    // NOTE: we have to put this here as well as in the `Browser.close` handler
53    // since browser shutdown can be initiated when the last tab is closed, e.g.
54    // with persistent context.
55    await Promise.all([
56      waitForAddonManager(),
57      waitForSearchService(),
58    ]);
59  }
60
61  async ['Browser.createBrowserContext']({removeOnDetach}) {
62    if (!this._enabled)
63      throw new Error('Browser domain is not enabled');
64    const browserContext = this._targetRegistry.createBrowserContext(removeOnDetach);
65    this._createdBrowserContextIds.add(browserContext.browserContextId);
66    return {browserContextId: browserContext.browserContextId};
67  }
68
69  async ['Browser.removeBrowserContext']({browserContextId}) {
70    if (!this._enabled)
71      throw new Error('Browser domain is not enabled');
72    await this._targetRegistry.browserContextForId(browserContextId).destroy();
73    this._createdBrowserContextIds.delete(browserContextId);
74  }
75
76  dispose() {
77    helper.removeListeners(this._eventListeners);
78    for (const [target, session] of this._attachedSessions)
79      this._dispatcher.destroySession(session);
80    this._attachedSessions.clear();
81    for (const browserContextId of this._createdBrowserContextIds) {
82      const browserContext = this._targetRegistry.browserContextForId(browserContextId);
83      if (browserContext.removeOnDetach)
84        browserContext.destroy();
85    }
86    this._createdBrowserContextIds.clear();
87  }
88
89  _shouldAttachToTarget(target) {
90    if (this._createdBrowserContextIds.has(target._browserContext.browserContextId))
91      return true;
92    return this._attachToDefaultContext && target._browserContext === this._targetRegistry.defaultContext();
93  }
94
95  _onTargetCreated(target) {
96    if (!this._shouldAttachToTarget(target))
97      return;
98    const channel = target.channel();
99    const session = this._dispatcher.createSession();
100    this._attachedSessions.set(target, session);
101    this._session.emitEvent('Browser.attachedToTarget', {
102      sessionId: session.sessionId(),
103      targetInfo: target.info()
104    });
105    session.setHandler(new PageHandler(target, session, channel));
106  }
107
108  _onTargetDestroyed(target) {
109    const session = this._attachedSessions.get(target);
110    if (!session)
111      return;
112    this._attachedSessions.delete(target);
113    this._dispatcher.destroySession(session);
114    this._session.emitEvent('Browser.detachedFromTarget', {
115      sessionId: session.sessionId(),
116      targetId: target.id(),
117    });
118  }
119
120  _onDownloadCreated(downloadInfo) {
121    this._session.emitEvent('Browser.downloadCreated', downloadInfo);
122  }
123
124  _onDownloadFinished(downloadInfo) {
125    this._session.emitEvent('Browser.downloadFinished', downloadInfo);
126  }
127
128  async ['Browser.cancelDownload']({uuid}) {
129    await this._targetRegistry.cancelDownload({uuid});
130  }
131
132  async ['Browser.newPage']({browserContextId}) {
133    const targetId = await this._targetRegistry.newPage({browserContextId});
134    return {targetId};
135  }
136
137  async ['Browser.close']() {
138    let browserWindow = Services.wm.getMostRecentWindow(
139      "navigator:browser"
140    );
141    if (browserWindow && browserWindow.gBrowserInit) {
142      // idleTasksFinishedPromise does not resolve when the window
143      // is closed early enough, so we race against window closure.
144      await Promise.race([
145        browserWindow.gBrowserInit.idleTasksFinishedPromise,
146        waitForWindowClosed(browserWindow),
147      ]);
148    }
149    // Try to fully initialize browser before closing.
150    // See comment in `Browser.enable`.
151    await Promise.all([
152      waitForAddonManager(),
153      waitForSearchService(),
154    ]);
155    this._onclose();
156    Services.startup.quit(Ci.nsIAppStartup.eForceQuit);
157  }
158
159  async ['Browser.grantPermissions']({browserContextId, origin, permissions}) {
160    await this._targetRegistry.browserContextForId(browserContextId).grantPermissions(origin, permissions);
161  }
162
163  async ['Browser.resetPermissions']({browserContextId}) {
164    this._targetRegistry.browserContextForId(browserContextId).resetPermissions();
165  }
166
167  ['Browser.setExtraHTTPHeaders']({browserContextId, headers}) {
168    this._targetRegistry.browserContextForId(browserContextId).extraHTTPHeaders = headers;
169  }
170
171  ['Browser.setHTTPCredentials']({browserContextId, credentials}) {
172    this._targetRegistry.browserContextForId(browserContextId).httpCredentials = nullToUndefined(credentials);
173  }
174
175  async ['Browser.setBrowserProxy']({type, host, port, bypass, username, password}) {
176    this._targetRegistry.setBrowserProxy({ type, host, port, bypass, username, password});
177  }
178
179  async ['Browser.setContextProxy']({browserContextId, type, host, port, bypass, username, password}) {
180    const browserContext = this._targetRegistry.browserContextForId(browserContextId);
181    browserContext.setProxy({ type, host, port, bypass, username, password });
182  }
183
184  ['Browser.setRequestInterception']({browserContextId, enabled}) {
185    this._targetRegistry.browserContextForId(browserContextId).requestInterceptionEnabled = enabled;
186  }
187
188  ['Browser.setIgnoreHTTPSErrors']({browserContextId, ignoreHTTPSErrors}) {
189    this._targetRegistry.browserContextForId(browserContextId).setIgnoreHTTPSErrors(nullToUndefined(ignoreHTTPSErrors));
190  }
191
192  ['Browser.setDownloadOptions']({browserContextId, downloadOptions}) {
193    this._targetRegistry.browserContextForId(browserContextId).downloadOptions = nullToUndefined(downloadOptions);
194  }
195
196  async ['Browser.setGeolocationOverride']({browserContextId, geolocation}) {
197    await this._targetRegistry.browserContextForId(browserContextId).applySetting('geolocation', nullToUndefined(geolocation));
198  }
199
200  async ['Browser.setOnlineOverride']({browserContextId, override}) {
201    await this._targetRegistry.browserContextForId(browserContextId).applySetting('onlineOverride', nullToUndefined(override));
202  }
203
204  async ['Browser.setColorScheme']({browserContextId, colorScheme}) {
205    await this._targetRegistry.browserContextForId(browserContextId).setColorScheme(nullToUndefined(colorScheme));
206  }
207
208  async ['Browser.setReducedMotion']({browserContextId, reducedMotion}) {
209    await this._targetRegistry.browserContextForId(browserContextId).setReducedMotion(nullToUndefined(reducedMotion));
210  }
211
212  async ['Browser.setForcedColors']({browserContextId, forcedColors}) {
213    await this._targetRegistry.browserContextForId(browserContextId).setForcedColors(nullToUndefined(forcedColors));
214  }
215
216  async ['Browser.setVideoRecordingOptions']({browserContextId, options}) {
217    await this._targetRegistry.browserContextForId(browserContextId).setVideoRecordingOptions(options);
218  }
219
220  async ['Browser.setUserAgentOverride']({browserContextId, userAgent}) {
221    await this._targetRegistry.browserContextForId(browserContextId).setDefaultUserAgent(userAgent);
222  }
223
224  async ['Browser.setPlatformOverride']({browserContextId, platform}) {
225    await this._targetRegistry.browserContextForId(browserContextId).setDefaultPlatform(platform);
226  }
227
228  async ['Browser.setBypassCSP']({browserContextId, bypassCSP}) {
229    await this._targetRegistry.browserContextForId(browserContextId).applySetting('bypassCSP', nullToUndefined(bypassCSP));
230  }
231
232  async ['Browser.setJavaScriptDisabled']({browserContextId, javaScriptDisabled}) {
233    await this._targetRegistry.browserContextForId(browserContextId).setJavaScriptDisabled(javaScriptDisabled);
234  }
235
236  async ['Browser.setLocaleOverride']({browserContextId, locale}) {
237    await this._targetRegistry.browserContextForId(browserContextId).applySetting('locale', nullToUndefined(locale));
238  }
239
240  async ['Browser.setTimezoneOverride']({browserContextId, timezoneId}) {
241    await this._targetRegistry.browserContextForId(browserContextId).applySetting('timezoneId', nullToUndefined(timezoneId));
242  }
243
244  async ['Browser.setTouchOverride']({browserContextId, hasTouch}) {
245    await this._targetRegistry.browserContextForId(browserContextId).setTouchOverride(nullToUndefined(hasTouch));
246  }
247
248  async ['Browser.setDefaultViewport']({browserContextId, viewport}) {
249    await this._targetRegistry.browserContextForId(browserContextId).setDefaultViewport(nullToUndefined(viewport));
250  }
251
252  async ['Browser.setScrollbarsHidden']({browserContextId, hidden}) {
253    await this._targetRegistry.browserContextForId(browserContextId).applySetting('scrollbarsHidden', nullToUndefined(hidden));
254  }
255
256  async ['Browser.addScriptToEvaluateOnNewDocument']({browserContextId, script}) {
257    await this._targetRegistry.browserContextForId(browserContextId).addScriptToEvaluateOnNewDocument(script);
258  }
259
260  async ['Browser.addBinding']({browserContextId, worldName, name, script}) {
261    await this._targetRegistry.browserContextForId(browserContextId).addBinding(worldName, name, script);
262  }
263
264  ['Browser.setCookies']({browserContextId, cookies}) {
265    this._targetRegistry.browserContextForId(browserContextId).setCookies(cookies);
266  }
267
268  ['Browser.clearCookies']({browserContextId}) {
269    this._targetRegistry.browserContextForId(browserContextId).clearCookies();
270  }
271
272  ['Browser.getCookies']({browserContextId}) {
273    const cookies = this._targetRegistry.browserContextForId(browserContextId).getCookies();
274    return {cookies};
275  }
276
277  async ['Browser.getInfo']() {
278    const version = AppConstants.MOZ_APP_VERSION_DISPLAY;
279    const userAgent = Components.classes["@mozilla.org/network/protocol;1?name=http"]
280                                .getService(Components.interfaces.nsIHttpProtocolHandler)
281                                .userAgent;
282    return {version: 'Firefox/' + version, userAgent};
283  }
284}
285
286async function waitForSearchService() {
287  const searchService = Components.classes["@mozilla.org/browser/search-service;1"].getService(Components.interfaces.nsISearchService);
288  await searchService.init();
289}
290
291async function waitForAddonManager() {
292  if (AddonManager.isReady)
293    return;
294  await new Promise(resolve => {
295    let listener = {
296      onStartup() {
297        AddonManager.removeManagerListener(listener);
298        resolve();
299      },
300      onShutdown() { },
301    };
302    AddonManager.addManagerListener(listener);
303  });
304}
305
306async function waitForWindowClosed(browserWindow) {
307  if (browserWindow.closed)
308    return;
309  await new Promise((resolve => {
310    const listener = {
311      onCloseWindow: window => {
312        let domWindow;
313        if (window instanceof Ci.nsIAppWindow)
314          domWindow = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
315        else
316          domWindow = window;
317        if (domWindow === browserWindow) {
318          Services.wm.removeListener(listener);
319          resolve();
320        }
321      },
322    };
323    Services.wm.addListener(listener);
324  }));
325}
326
327function nullToUndefined(value) {
328  return value === null ? undefined : value;
329}
330
331var EXPORTED_SYMBOLS = ['BrowserHandler'];
332this.BrowserHandler = BrowserHandler;
333
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)