Best JavaScript code snippet using playwright-internal
TargetRegistry.js
Source:TargetRegistry.js
...156 target.updateForcedColorsOverride();157 if (!hasExplicitSize)158 target.updateViewportSize();159 if (browserContext.videoRecordingOptions)160 target._startVideoRecording(browserContext.videoRecordingOptions);161 };162 const onTabCloseListener = event => {163 const tab = event.target;164 const linkedBrowser = tab.linkedBrowser;165 const target = this._browserToTarget.get(linkedBrowser);166 if (target)167 target.dispose();168 };169 const domWindowTabListeners = new Map();170 const onOpenWindow = async (appWindow) => {171 let domWindow;172 if (appWindow instanceof Ci.nsIAppWindow) {173 domWindow = appWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);174 } else {175 domWindow = appWindow;176 appWindow = null;177 }178 if (!(domWindow instanceof Ci.nsIDOMChromeWindow))179 return;180 // In persistent mode, window might be opened long ago and might be181 // already initialized.182 //183 // In this case, we want to keep this callback synchronous so that we will call184 // `onTabOpenListener` synchronously and before the sync IPc message `juggler:content-ready`.185 if (domWindow.document.readyState === 'uninitialized' || domWindow.document.readyState === 'loading') {186 // For non-initialized windows, DOMContentLoaded initializes gBrowser187 // and starts tab loading (see //browser/base/content/browser.js), so we188 // are guaranteed to call `onTabOpenListener` before the sync IPC message189 // `juggler:content-ready`.190 await helper.awaitEvent(domWindow, 'DOMContentLoaded');191 }192 if (!domWindow.gBrowser)193 return;194 const tabContainer = domWindow.gBrowser.tabContainer;195 domWindowTabListeners.set(domWindow, [196 helper.addEventListener(tabContainer, 'TabOpen', event => onTabOpenListener(appWindow, domWindow, event)),197 helper.addEventListener(tabContainer, 'TabClose', onTabCloseListener),198 ]);199 for (const tab of domWindow.gBrowser.tabs)200 onTabOpenListener(appWindow, domWindow, { target: tab });201 };202 const onCloseWindow = window => {203 const domWindow = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);204 if (!(domWindow instanceof Ci.nsIDOMChromeWindow))205 return;206 if (!domWindow.gBrowser)207 return;208 const listeners = domWindowTabListeners.get(domWindow) || [];209 domWindowTabListeners.delete(domWindow);210 helper.removeListeners(listeners);211 for (const tab of domWindow.gBrowser.tabs)212 onTabCloseListener({ target: tab });213 };214 const extHelperAppSvc = Cc["@mozilla.org/uriloader/external-helper-app-service;1"].getService(Ci.nsIExternalHelperAppService);215 this._downloadInterceptor = new DownloadInterceptor(this);216 extHelperAppSvc.setDownloadInterceptor(this._downloadInterceptor);217 Services.wm.addListener({ onOpenWindow, onCloseWindow });218 for (const win of Services.wm.getEnumerator(null))219 onOpenWindow(win);220 }221 async cancelDownload(options) {222 this._downloadInterceptor.cancelDownload(options.uuid);223 }224 setBrowserProxy(proxy) {225 this._browserProxy = proxy;226 }227 getProxyInfo(channel) {228 const originAttributes = channel.loadInfo && channel.loadInfo.originAttributes;229 const browserContext = originAttributes ? this.browserContextForUserContextId(originAttributes.userContextId) : null;230 // Prefer context proxy and fallback to browser-level proxy.231 const proxyInfo = (browserContext && browserContext._proxy) || this._browserProxy;232 if (!proxyInfo || proxyInfo.bypass.some(domainSuffix => channel.URI.host.endsWith(domainSuffix)))233 return null;234 return proxyInfo;235 }236 defaultContext() {237 return this._defaultContext;238 }239 createBrowserContext(removeOnDetach) {240 return new BrowserContext(this, helper.generateId(), removeOnDetach);241 }242 browserContextForId(browserContextId) {243 return this._browserContextIdToBrowserContext.get(browserContextId);244 }245 browserContextForUserContextId(userContextId) {246 return this._userContextIdToBrowserContext.get(userContextId);247 }248 async newPage({browserContextId}) {249 const browserContext = this.browserContextForId(browserContextId);250 const features = "chrome,dialog=no,all";251 // See _callWithURIToLoad in browser.js for the structure of window.arguments252 // window.arguments[1]: unused (bug 871161)253 // [2]: referrerInfo (nsIReferrerInfo)254 // [3]: postData (nsIInputStream)255 // [4]: allowThirdPartyFixup (bool)256 // [5]: userContextId (int)257 // [6]: originPrincipal (nsIPrincipal)258 // [7]: originStoragePrincipal (nsIPrincipal)259 // [8]: triggeringPrincipal (nsIPrincipal)260 // [9]: allowInheritPrincipal (bool)261 // [10]: csp (nsIContentSecurityPolicy)262 // [11]: nsOpenWindowInfo263 const args = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);264 const urlSupports = Cc["@mozilla.org/supports-string;1"].createInstance(265 Ci.nsISupportsString266 );267 urlSupports.data = 'about:blank';268 args.appendElement(urlSupports); // 0269 args.appendElement(undefined); // 1270 args.appendElement(undefined); // 2271 args.appendElement(undefined); // 3272 args.appendElement(undefined); // 4273 const userContextIdSupports = Cc[274 "@mozilla.org/supports-PRUint32;1"275 ].createInstance(Ci.nsISupportsPRUint32);276 userContextIdSupports.data = browserContext.userContextId;277 args.appendElement(userContextIdSupports); // 5278 args.appendElement(undefined); // 6279 args.appendElement(undefined); // 7280 args.appendElement(Services.scriptSecurityManager.getSystemPrincipal()); // 8281 const window = Services.ww.openWindow(null, AppConstants.BROWSER_CHROME_URL, '_blank', features, args);282 await waitForWindowReady(window);283 if (window.gBrowser.browsers.length !== 1)284 throw new Error(`Unexpected number of tabs in the new window: ${window.gBrowser.browsers.length}`);285 const browser = window.gBrowser.browsers[0];286 const target = this._browserToTarget.get(browser);287 browser.focus();288 if (browserContext.settings.timezoneId) {289 if (await target.hasFailedToOverrideTimezone())290 throw new Error('Failed to override timezone');291 }292 return target.id();293 }294 targets() {295 return Array.from(this._browserToTarget.values());296 }297 targetForBrowser(browser) {298 return this._browserToTarget.get(browser);299 }300}301class PageTarget {302 constructor(registry, win, tab, browserContext, opener) {303 EventEmitter.decorate(this);304 this._targetId = helper.generateId();305 this._registry = registry;306 this._window = win;307 this._gBrowser = win.gBrowser;308 this._tab = tab;309 this._linkedBrowser = tab.linkedBrowser;310 this._browserContext = browserContext;311 this._viewportSize = undefined;312 this._initialDPPX = this._linkedBrowser.browsingContext.overrideDPPX;313 this._url = 'about:blank';314 this._openerId = opener ? opener.id() : undefined;315 this._channel = SimpleChannel.createForMessageManager(`browser::page[${this._targetId}]`, this._linkedBrowser.messageManager);316 this._videoRecordingInfo = undefined;317 this._screencastRecordingInfo = undefined;318 this._dialogs = new Map();319 this.forcedColors = 'no-override';320 const navigationListener = {321 QueryInterface: ChromeUtils.generateQI([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]),322 onLocationChange: (aWebProgress, aRequest, aLocation) => this._onNavigated(aLocation),323 };324 this._eventListeners = [325 helper.addObserver(this._updateModalDialogs.bind(this), 'tabmodal-dialog-loaded'),326 helper.addProgressListener(tab.linkedBrowser, navigationListener, Ci.nsIWebProgress.NOTIFY_LOCATION),327 helper.addEventListener(this._linkedBrowser, 'DOMModalDialogClosed', event => this._updateModalDialogs()),328 ];329 this._disposed = false;330 browserContext.pages.add(this);331 this._registry._browserToTarget.set(this._linkedBrowser, this);332 this._registry._browserBrowsingContextToTarget.set(this._linkedBrowser.browsingContext, this);333 this._registry.emit(TargetRegistry.Events.TargetCreated, this);334 }335 dialog(dialogId) {336 return this._dialogs.get(dialogId);337 }338 dialogs() {339 return [...this._dialogs.values()];340 }341 async windowReady() {342 await waitForWindowReady(this._window);343 }344 linkedBrowser() {345 return this._linkedBrowser;346 }347 browserContext() {348 return this._browserContext;349 }350 updateTouchOverride() {351 this._linkedBrowser.browsingContext.touchEventsOverride = this._browserContext.touchOverride ? 'enabled' : 'none';352 }353 updateUserAgent() {354 this._linkedBrowser.browsingContext.customUserAgent = this._browserContext.defaultUserAgent;355 }356 updatePlatform() {357 this._linkedBrowser.browsingContext.customPlatform = this._browserContext.defaultPlatform;358 }359 updateJavaScriptDisabled() {360 this._linkedBrowser.browsingContext.allowJavascript = !this._browserContext.javaScriptDisabled;361 }362 _updateModalDialogs() {363 const prompts = new Set(this._linkedBrowser.tabModalPromptBox ? this._linkedBrowser.tabModalPromptBox.listPrompts() : []);364 for (const dialog of this._dialogs.values()) {365 if (!prompts.has(dialog.prompt())) {366 this._dialogs.delete(dialog.id());367 this.emit(PageTarget.Events.DialogClosed, dialog);368 } else {369 prompts.delete(dialog.prompt());370 }371 }372 for (const prompt of prompts) {373 const dialog = Dialog.createIfSupported(prompt);374 if (!dialog)375 continue;376 this._dialogs.set(dialog.id(), dialog);377 this.emit(PageTarget.Events.DialogOpened, dialog);378 }379 }380 async updateViewportSize() {381 // Viewport size is defined by three arguments:382 // 1. default size. Could be explicit if set as part of `window.open` call, e.g.383 // `window.open(url, title, 'width=400,height=400')`384 // 2. page viewport size385 // 3. browserContext viewport size386 //387 // The "default size" (1) is only respected when the page is opened.388 // Otherwise, explicitly set page viewport prevales over browser context389 // default viewport.390 const viewportSize = this._viewportSize || this._browserContext.defaultViewportSize;391 const actualSize = await setViewportSizeForBrowser(viewportSize, this._linkedBrowser, this._window);392 this._linkedBrowser.browsingContext.overrideDPPX = this._browserContext.deviceScaleFactor || this._initialDPPX;393 await this._channel.connect('').send('awaitViewportDimensions', {394 width: actualSize.width,395 height: actualSize.height,396 deviceSizeIsPageSize: !!this._browserContext.deviceScaleFactor,397 });398 }399 setEmulatedMedia(mediumOverride) {400 this._linkedBrowser.browsingContext.mediumOverride = mediumOverride || '';401 }402 setColorScheme(colorScheme) {403 this.colorScheme = fromProtocolColorScheme(colorScheme);404 this.updateColorSchemeOverride();405 }406 updateColorSchemeOverride() {407 this._linkedBrowser.browsingContext.prefersColorSchemeOverride = this.colorScheme || this._browserContext.colorScheme || 'none';408 }409 setReducedMotion(reducedMotion) {410 this.reducedMotion = fromProtocolReducedMotion(reducedMotion);411 this.updateReducedMotionOverride();412 }413 updateReducedMotionOverride() {414 this._linkedBrowser.browsingContext.prefersReducedMotionOverride = this.reducedMotion || this._browserContext.reducedMotion || 'none';415 }416 setForcedColors(forcedColors) {417 this.forcedColors = fromProtocolForcedColors(forcedColors);418 this.updateForcedColorsOverride();419 }420 updateForcedColorsOverride() {421 this._linkedBrowser.browsingContext.forcedColorsOverride = (this.forcedColors !== 'no-override' ? this.forcedColors : this._browserContext.forcedColors) || 'no-override';422 }423 async setViewportSize(viewportSize) {424 this._viewportSize = viewportSize;425 await this.updateViewportSize();426 }427 close(runBeforeUnload = false) {428 this._gBrowser.removeTab(this._tab, {429 skipPermitUnload: !runBeforeUnload,430 });431 }432 channel() {433 return this._channel;434 }435 id() {436 return this._targetId;437 }438 info() {439 return {440 targetId: this.id(),441 type: 'page',442 browserContextId: this._browserContext.browserContextId,443 openerId: this._openerId,444 };445 }446 _onNavigated(aLocation) {447 this._url = aLocation.spec;448 this._browserContext.grantPermissionsToOrigin(this._url);449 }450 async ensurePermissions() {451 await this._channel.connect('').send('ensurePermissions', {}).catch(e => void e);452 }453 async addScriptToEvaluateOnNewDocument(script) {454 await this._channel.connect('').send('addScriptToEvaluateOnNewDocument', script).catch(e => void e);455 }456 async addBinding(worldName, name, script) {457 await this._channel.connect('').send('addBinding', { worldName, name, script }).catch(e => void e);458 }459 async applyContextSetting(name, value) {460 await this._channel.connect('').send('applyContextSetting', { name, value }).catch(e => void e);461 }462 async hasFailedToOverrideTimezone() {463 return await this._channel.connect('').send('hasFailedToOverrideTimezone').catch(e => true);464 }465 async _startVideoRecording({width, height, dir}) {466 // On Mac the window may not yet be visible when TargetCreated and its467 // NSWindow.windowNumber may be -1, so we wait until the window is known468 // to be initialized and visible.469 await this.windowReady();470 const file = OS.Path.join(dir, helper.generateId() + '.webm');471 if (width < 10 || width > 10000 || height < 10 || height > 10000)472 throw new Error("Invalid size");473 const docShell = this._gBrowser.ownerGlobal.docShell;474 // Exclude address bar and navigation control from the video.475 const rect = this.linkedBrowser().getBoundingClientRect();476 const devicePixelRatio = this._window.devicePixelRatio;477 let sessionId;478 const registry = this._registry;479 const screencastClient = {480 QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),481 screencastFrame(data, deviceWidth, deviceHeight) {482 },483 screencastStopped() {484 registry.emit(TargetRegistry.Events.ScreencastStopped, sessionId);485 },486 };487 const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };488 sessionId = screencastService.startVideoRecording(screencastClient, docShell, true, file, width, height, 0, viewport.width, viewport.height, devicePixelRatio * rect.top);489 this._videoRecordingInfo = { sessionId, file };490 this.emit(PageTarget.Events.ScreencastStarted);491 }492 _stopVideoRecording() {493 if (!this._videoRecordingInfo)494 throw new Error('No video recording in progress');495 const videoRecordingInfo = this._videoRecordingInfo;496 this._videoRecordingInfo = undefined;497 screencastService.stopVideoRecording(videoRecordingInfo.sessionId);498 }499 videoRecordingInfo() {500 return this._videoRecordingInfo;501 }502 async startScreencast({ width, height, quality }) {503 // On Mac the window may not yet be visible when TargetCreated and its504 // NSWindow.windowNumber may be -1, so we wait until the window is known505 // to be initialized and visible.506 await this.windowReady();507 if (width < 10 || width > 10000 || height < 10 || height > 10000)508 throw new Error("Invalid size");509 const docShell = this._gBrowser.ownerGlobal.docShell;510 // Exclude address bar and navigation control from the video.511 const rect = this.linkedBrowser().getBoundingClientRect();512 const devicePixelRatio = this._window.devicePixelRatio;513 const self = this;514 const screencastClient = {515 QueryInterface: ChromeUtils.generateQI([Ci.nsIScreencastServiceClient]),516 screencastFrame(data, deviceWidth, deviceHeight) {517 if (self._screencastRecordingInfo)518 self.emit(PageTarget.Events.ScreencastFrame, { data, deviceWidth, deviceHeight });519 },520 screencastStopped() {521 },522 };523 const viewport = this._viewportSize || this._browserContext.defaultViewportSize || { width: 0, height: 0 };524 const screencastId = screencastService.startVideoRecording(screencastClient, docShell, false, '', width, height, quality || 90, viewport.width, viewport.height, devicePixelRatio * rect.top);525 this._screencastRecordingInfo = { screencastId };526 return { screencastId };527 }528 screencastFrameAck({ screencastId }) {529 if (!this._screencastRecordingInfo || this._screencastRecordingInfo.screencastId !== screencastId)530 return;531 screencastService.screencastFrameAck(screencastId);532 }533 stopScreencast() {534 if (!this._screencastRecordingInfo)535 throw new Error('No screencast in progress');536 const { screencastId } = this._screencastRecordingInfo;537 this._screencastRecordingInfo = undefined;538 screencastService.stopVideoRecording(screencastId);539 }540 dispose() {541 this._disposed = true;542 if (this._videoRecordingInfo)543 this._stopVideoRecording();544 if (this._screencastRecordingInfo)545 this.stopScreencast();546 this._browserContext.pages.delete(this);547 this._registry._browserToTarget.delete(this._linkedBrowser);548 this._registry._browserBrowsingContextToTarget.delete(this._linkedBrowser.browsingContext);549 try {550 helper.removeListeners(this._eventListeners);551 } catch (e) {552 // In some cases, removing listeners from this._linkedBrowser fails553 // because it is already half-destroyed.554 if (e)555 dump(e.message + '\n' + e.stack + '\n');556 }557 this._registry.emit(TargetRegistry.Events.TargetDestroyed, this);558 }559}560PageTarget.Events = {561 ScreencastStarted: Symbol('PageTarget.ScreencastStarted'),562 ScreencastFrame: Symbol('PageTarget.ScreencastFrame'),563 Crashed: Symbol('PageTarget.Crashed'),564 DialogOpened: Symbol('PageTarget.DialogOpened'),565 DialogClosed: Symbol('PageTarget.DialogClosed'),566};567function fromProtocolColorScheme(colorScheme) {568 if (colorScheme === 'light' || colorScheme === 'dark')569 return colorScheme;570 if (colorScheme === null || colorScheme === 'no-preference')571 return undefined;572 throw new Error('Unknown color scheme: ' + colorScheme);573}574function fromProtocolReducedMotion(reducedMotion) {575 if (reducedMotion === 'reduce' || reducedMotion === 'no-preference')576 return reducedMotion;577 if (reducedMotion === null)578 return undefined;579 throw new Error('Unknown reduced motion: ' + reducedMotion);580}581function fromProtocolForcedColors(forcedColors) {582 if (forcedColors === 'active' || forcedColors === 'none')583 return forcedColors;584 if (forcedColors === null)585 return undefined;586 throw new Error('Unknown forced colors: ' + forcedColors);587}588class BrowserContext {589 constructor(registry, browserContextId, removeOnDetach) {590 this._registry = registry;591 this.browserContextId = browserContextId;592 // Default context has userContextId === 0, but we pass undefined to many APIs just in case.593 this.userContextId = 0;594 if (browserContextId !== undefined) {595 const identity = ContextualIdentityService.create(IDENTITY_NAME + browserContextId);596 this.userContextId = identity.userContextId;597 }598 this._principals = [];599 // Maps origins to the permission lists.600 this._permissions = new Map();601 this._registry._browserContextIdToBrowserContext.set(this.browserContextId, this);602 this._registry._userContextIdToBrowserContext.set(this.userContextId, this);603 this._proxy = null;604 this.removeOnDetach = removeOnDetach;605 this.extraHTTPHeaders = undefined;606 this.httpCredentials = undefined;607 this.requestInterceptionEnabled = undefined;608 this.ignoreHTTPSErrors = undefined;609 this.downloadOptions = undefined;610 this.defaultViewportSize = undefined;611 this.deviceScaleFactor = undefined;612 this.defaultUserAgent = null;613 this.defaultPlatform = null;614 this.javaScriptDisabled = false;615 this.touchOverride = false;616 this.colorScheme = 'none';617 this.forcedColors = 'no-override';618 this.reducedMotion = 'none';619 this.videoRecordingOptions = undefined;620 this.scriptsToEvaluateOnNewDocument = [];621 this.bindings = [];622 this.settings = {};623 this.pages = new Set();624 }625 setColorScheme(colorScheme) {626 this.colorScheme = fromProtocolColorScheme(colorScheme);627 for (const page of this.pages)628 page.updateColorSchemeOverride();629 }630 setReducedMotion(reducedMotion) {631 this.reducedMotion = fromProtocolReducedMotion(reducedMotion);632 for (const page of this.pages)633 page.updateReducedMotionOverride();634 }635 setForcedColors(forcedColors) {636 this.forcedColors = fromProtocolForcedColors(forcedColors);637 for (const page of this.pages)638 page.updateForcedColorsOverride();639 }640 async destroy() {641 if (this.userContextId !== 0) {642 ContextualIdentityService.remove(this.userContextId);643 for (const page of this.pages)644 page.close();645 if (this.pages.size) {646 await new Promise(f => {647 const listener = helper.on(this._registry, TargetRegistry.Events.TargetDestroyed, () => {648 if (!this.pages.size) {649 helper.removeListeners([listener]);650 f();651 }652 });653 });654 }655 }656 this._registry._browserContextIdToBrowserContext.delete(this.browserContextId);657 this._registry._userContextIdToBrowserContext.delete(this.userContextId);658 }659 setProxy(proxy) {660 // Clear AuthCache.661 Services.obs.notifyObservers(null, "net:clear-active-logins");662 this._proxy = proxy;663 }664 setIgnoreHTTPSErrors(ignoreHTTPSErrors) {665 if (this.ignoreHTTPSErrors === ignoreHTTPSErrors)666 return;667 this.ignoreHTTPSErrors = ignoreHTTPSErrors;668 const certOverrideService = Cc[669 "@mozilla.org/security/certoverride;1"670 ].getService(Ci.nsICertOverrideService);671 if (ignoreHTTPSErrors) {672 Preferences.set("network.stricttransportsecurity.preloadlist", false);673 Preferences.set("security.cert_pinning.enforcement_level", 0);674 certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(true, this.userContextId);675 } else {676 certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(false, this.userContextId);677 }678 }679 setDefaultUserAgent(userAgent) {680 this.defaultUserAgent = userAgent;681 for (const page of this.pages)682 page.updateUserAgent();683 }684 setDefaultPlatform(platform) {685 this.defaultPlatform = platform;686 for (const page of this.pages)687 page.updatePlatform();688 }689 setJavaScriptDisabled(javaScriptDisabled) {690 this.javaScriptDisabled = javaScriptDisabled;691 for (const page of this.pages)692 page.updateJavaScriptDisabled();693 }694 setTouchOverride(touchOverride) {695 this.touchOverride = touchOverride;696 for (const page of this.pages)697 page.updateTouchOverride();698 }699 async setDefaultViewport(viewport) {700 this.defaultViewportSize = viewport ? viewport.viewportSize : undefined;701 this.deviceScaleFactor = viewport ? viewport.deviceScaleFactor : undefined;702 await Promise.all(Array.from(this.pages).map(page => page.updateViewportSize()));703 }704 async addScriptToEvaluateOnNewDocument(script) {705 this.scriptsToEvaluateOnNewDocument.push(script);706 await Promise.all(Array.from(this.pages).map(page => page.addScriptToEvaluateOnNewDocument(script)));707 }708 async addBinding(worldName, name, script) {709 this.bindings.push({ worldName, name, script });710 await Promise.all(Array.from(this.pages).map(page => page.addBinding(worldName, name, script)));711 }712 async applySetting(name, value) {713 this.settings[name] = value;714 await Promise.all(Array.from(this.pages).map(page => page.applyContextSetting(name, value)));715 }716 async grantPermissions(origin, permissions) {717 this._permissions.set(origin, permissions);718 const promises = [];719 for (const page of this.pages) {720 if (origin === '*' || page._url.startsWith(origin)) {721 this.grantPermissionsToOrigin(page._url);722 promises.push(page.ensurePermissions());723 }724 }725 await Promise.all(promises);726 }727 resetPermissions() {728 for (const principal of this._principals) {729 for (const permission of ALL_PERMISSIONS)730 Services.perms.removeFromPrincipal(principal, permission);731 }732 this._principals = [];733 this._permissions.clear();734 }735 grantPermissionsToOrigin(url) {736 let origin = Array.from(this._permissions.keys()).find(key => url.startsWith(key));737 if (!origin)738 origin = '*';739 const permissions = this._permissions.get(origin);740 if (!permissions)741 return;742 const attrs = { userContextId: this.userContextId || undefined };743 const principal = Services.scriptSecurityManager.createContentPrincipal(NetUtil.newURI(url), attrs);744 this._principals.push(principal);745 for (const permission of ALL_PERMISSIONS) {746 const action = permissions.includes(permission) ? Ci.nsIPermissionManager.ALLOW_ACTION : Ci.nsIPermissionManager.DENY_ACTION;747 Services.perms.addFromPrincipal(principal, permission, action, Ci.nsIPermissionManager.EXPIRE_NEVER, 0 /* expireTime */);748 }749 }750 setCookies(cookies) {751 const protocolToSameSite = {752 [undefined]: Ci.nsICookie.SAMESITE_NONE,753 'Lax': Ci.nsICookie.SAMESITE_LAX,754 'Strict': Ci.nsICookie.SAMESITE_STRICT,755 };756 for (const cookie of cookies) {757 const uri = cookie.url ? NetUtil.newURI(cookie.url) : null;758 let domain = cookie.domain;759 if (!domain) {760 if (!uri)761 throw new Error('At least one of the url and domain needs to be specified');762 domain = uri.host;763 }764 let path = cookie.path;765 if (!path)766 path = uri ? dirPath(uri.filePath) : '/';767 let secure = false;768 if (cookie.secure !== undefined)769 secure = cookie.secure;770 else if (uri && uri.scheme === 'https')771 secure = true;772 Services.cookies.add(773 domain,774 path,775 cookie.name,776 cookie.value,777 secure,778 cookie.httpOnly || false,779 cookie.expires === undefined || cookie.expires === -1 /* isSession */,780 cookie.expires === undefined ? Date.now() + HUNDRED_YEARS : cookie.expires,781 { userContextId: this.userContextId || undefined } /* originAttributes */,782 protocolToSameSite[cookie.sameSite],783 Ci.nsICookie.SCHEME_UNSET784 );785 }786 }787 clearCookies() {788 Services.cookies.removeCookiesWithOriginAttributes(JSON.stringify({ userContextId: this.userContextId || undefined }));789 }790 getCookies() {791 const result = [];792 const sameSiteToProtocol = {793 [Ci.nsICookie.SAMESITE_NONE]: 'None',794 [Ci.nsICookie.SAMESITE_LAX]: 'Lax',795 [Ci.nsICookie.SAMESITE_STRICT]: 'Strict',796 };797 for (let cookie of Services.cookies.cookies) {798 if (cookie.originAttributes.userContextId !== this.userContextId)799 continue;800 if (cookie.host === 'addons.mozilla.org')801 continue;802 result.push({803 name: cookie.name,804 value: cookie.value,805 domain: cookie.host,806 path: cookie.path,807 expires: cookie.isSession ? -1 : cookie.expiry,808 size: cookie.name.length + cookie.value.length,809 httpOnly: cookie.isHttpOnly,810 secure: cookie.isSecure,811 session: cookie.isSession,812 sameSite: sameSiteToProtocol[cookie.sameSite],813 });814 }815 return result;816 }817 async setVideoRecordingOptions(options) {818 this.videoRecordingOptions = options;819 const promises = [];820 for (const page of this.pages) {821 if (options)822 promises.push(page._startVideoRecording(options));823 else if (page._videoRecordingInfo)824 promises.push(page._stopVideoRecording());825 }826 await Promise.all(promises);827 }828}829class Dialog {830 static createIfSupported(prompt) {831 const type = prompt.args.promptType;832 switch (type) {833 case 'alert':834 case 'alertCheck':835 return new Dialog(prompt, 'alert');836 case 'prompt':...
ViroARSceneNavigator.js
Source:ViroARSceneNavigator.js
...354 fileName - name of the file (without extension)355 saveToCameraRoll - whether or not the file should also be saved to the camera roll356 onError - callback function that accepts an errorCode.357 */358 _startVideoRecording(fileName, saveToCameraRoll, onError) {359 ViroARSceneNavigatorModule.startVideoRecording(findNodeHandle(this), fileName, saveToCameraRoll, onError);360 },361 /*362 Stops recording video of the Viro renderer363 returns Object w/ success, url and errorCode keys.364 */365 async _stopVideoRecording() {366 return await ViroARSceneNavigatorModule.stopVideoRecording(findNodeHandle(this));367 },368 /*369 Takes a screenshot of the Viro renderer370 fileName - name of the file (without extension)371 saveToCameraRoll - whether or not the file should also be saved to the camera roll372 returns Object w/ success, url and errorCode keys....
ARSceneNavigator.js
Source:ARSceneNavigator.js
...354 fileName - name of the file (without extension)355 saveToCameraRoll - whether or not the file should also be saved to the camera roll356 onError - callback function that accepts an errorCode.357 */358 _startVideoRecording(fileName, saveToCameraRoll, onError) {359 ARSceneNavigatorModule.startVideoRecording(findNodeHandle(this), fileName, saveToCameraRoll, onError);360 },361 /*362 Stops recording video of the Viro renderer363 returns Object w/ success, url and errorCode keys.364 */365 async _stopVideoRecording() {366 return await ARSceneNavigatorModule.stopVideoRecording(findNodeHandle(this));367 },368 /*369 Takes a screenshot of the Viro renderer370 fileName - name of the file (without extension)371 saveToCameraRoll - whether or not the file should also be saved to the camera roll372 returns Object w/ success, url and errorCode keys....
main.js
Source:main.js
...175 176 timer.addEventListener('secondsUpdated', function (e) {177 if(timer.getTimeValues().seconds == 1){178 videoCapture = new VideoCapture();179 videoCapture._startVideoRecording();180 }181 if(timer.getTimeValues().seconds == 7){182 videoCapture._stopVideoRecording();183 videoCapture = null;184 }185 });186 timer.addEventListener('targetAchieved', function (e) {187 timer.reset();188 });189 screenCapture = new ScreenSharing();190 screenCapture._startCapturing();191 }192 else if(data.status == "error"){193 alert("Exam not Found");...
videoCapture.js
Source:videoCapture.js
...10 } catch (e) {11 console.error('navigator.getUserMedia error:', e);12 }13 }14 async _startVideoRecording(e) {15 this.stream = await VideoCapture._startVideoCapture();16 this.recordedBlobs = [];17 try {18 this.mediaRecorder = new MediaRecorder(this.stream, {mimeType: 'video/webm'});19 } catch (e) {20 console.error('Exception while creating MediaRecorder:', e);21 return;22 }23 this.mediaRecorder.addEventListener('dataavailable', event => {24 if (event.data && event.data.size > 0) {25 this.recordedBlobs.push(event.data);26 }27 });28 this.mediaRecorder.start(10);...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!