Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js
...368 await this._crPage._browserContext._ensureVideosPath(); // Note: it is important to start video recorder before sending Page.startScreencast,369 // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.370 await this._createVideoRecorder(screencastId, screencastOptions);371 this._crPage.pageOrError().then(p => {372 if (p instanceof Error) this._stopVideoRecording().catch(() => {});373 });374 }375 let lifecycleEventsEnabled;376 if (!this._isMainFrame()) this._addRendererListeners();377 this._addBrowserListeners();378 const promises = [this._client.send('Page.enable'), this._client.send('Page.getFrameTree').then(({379 frameTree380 }) => {381 if (this._isMainFrame()) {382 this._handleFrameTree(frameTree);383 this._addRendererListeners();384 }385 const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)];386 for (const frame of localFrames) {387 // Note: frames might be removed before we send these.388 this._client._sendMayFail('Page.createIsolatedWorld', {389 frameId: frame._id,390 grantUniveralAccess: true,391 worldName: UTILITY_WORLD_NAME392 });393 for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source, false, undefined).catch(e => {});394 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});395 }396 const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';397 if (isInitialEmptyPage) {398 // Ignore lifecycle events for the initial empty page. It is never the final page399 // hence we are going to get more lifecycle updates after the actual navigation has400 // started (even if the target url is about:blank).401 lifecycleEventsEnabled.catch(e => {}).then(() => {402 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));403 });404 } else {405 this._firstNonInitialNavigationCommittedFulfill();406 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));407 }408 }), this._client.send('Log.enable', {}), lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', {409 enabled: true410 }), this._client.send('Runtime.enable', {}), this._client.send('Page.addScriptToEvaluateOnNewDocument', {411 source: '',412 worldName: UTILITY_WORLD_NAME413 }), this._networkManager.initialize(), this._client.send('Target.setAutoAttach', {414 autoAttach: true,415 waitForDebuggerOnStart: true,416 flatten: true417 })];418 if (this._isMainFrame()) promises.push(this._client.send('Emulation.setFocusEmulationEnabled', {419 enabled: true420 }));421 const options = this._crPage._browserContext._options;422 if (options.bypassCSP) promises.push(this._client.send('Page.setBypassCSP', {423 enabled: true424 }));425 if (options.ignoreHTTPSErrors) promises.push(this._client.send('Security.setIgnoreCertificateErrors', {426 ignore: true427 }));428 if (this._isMainFrame()) promises.push(this._updateViewport());429 if (options.hasTouch) promises.push(this._client.send('Emulation.setTouchEmulationEnabled', {430 enabled: true431 }));432 if (options.javaScriptEnabled === false) promises.push(this._client.send('Emulation.setScriptExecutionDisabled', {433 value: true434 }));435 if (options.userAgent || options.locale) promises.push(this._client.send('Emulation.setUserAgentOverride', {436 userAgent: options.userAgent || '',437 acceptLanguage: options.locale438 }));439 if (options.locale) promises.push(emulateLocale(this._client, options.locale));440 if (options.timezoneId) promises.push(emulateTimezone(this._client, options.timezoneId));441 promises.push(this._updateGeolocation(true));442 promises.push(this._updateExtraHTTPHeaders(true));443 promises.push(this._updateRequestInterception());444 promises.push(this._updateOffline(true));445 promises.push(this._updateHttpCredentials(true));446 promises.push(this._updateEmulateMedia(true));447 for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));448 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));449 for (const source of this._crPage._page._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));450 if (screencastOptions) promises.push(this._startVideoRecording(screencastOptions));451 promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));452 promises.push(this._firstNonInitialNavigationCommittedPromise);453 await Promise.all(promises);454 }455 dispose() {456 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);457 this._networkManager.dispose();458 this._crPage._sessions.delete(this._targetId);459 }460 async _navigate(frame, url, referrer) {461 const response = await this._client.send('Page.navigate', {462 url,463 referrer,464 frameId: frame._id465 });466 if (response.errorText) throw new Error(`${response.errorText} at ${url}`);467 return {468 newDocumentId: response.loaderId469 };470 }471 _onLifecycleEvent(event) {472 if (this._eventBelongsToStaleFrame(event.frameId)) return;473 if (event.name === 'load') this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');else if (event.name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');474 }475 _onFrameStoppedLoading(frameId) {476 if (this._eventBelongsToStaleFrame(frameId)) return;477 this._page._frameManager.frameStoppedLoading(frameId);478 }479 _handleFrameTree(frameTree) {480 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);481 this._onFrameNavigated(frameTree.frame, true);482 if (!frameTree.childFrames) return;483 for (const child of frameTree.childFrames) this._handleFrameTree(child);484 }485 _eventBelongsToStaleFrame(frameId) {486 const frame = this._page._frameManager.frame(frameId); // Subtree may be already gone because some ancestor navigation destroyed the oopif.487 if (!frame) return true; // When frame goes remote, parent process may still send some events488 // related to the local frame before it sends frameDetached.489 // In this case, we already have a new session for this frame, so events490 // in the old session should be ignored.491 const session = this._crPage._sessionForFrame(frame);492 return session && session !== this && !session._swappedIn;493 }494 _onFrameAttached(frameId, parentFrameId) {495 const frameSession = this._crPage._sessions.get(frameId);496 if (frameSession && frameId !== this._targetId) {497 // This is a remote -> local frame transition.498 frameSession._swappedIn = true;499 const frame = this._page._frameManager.frame(frameId); // Frame or even a whole subtree may be already gone, because some ancestor did navigate.500 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);501 return;502 }503 if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {504 // Parent frame may be gone already because some ancestor frame navigated and505 // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.506 // Be careful to not confuse this with "main frame navigated cross-process" scenario507 // where parentFrameId is null.508 return;509 }510 this._page._frameManager.frameAttached(frameId, parentFrameId);511 }512 _onFrameNavigated(framePayload, initial) {513 if (this._eventBelongsToStaleFrame(framePayload.id)) return;514 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);515 if (!initial) this._firstNonInitialNavigationCommittedFulfill();516 }517 _onFrameRequestedNavigation(payload) {518 if (this._eventBelongsToStaleFrame(payload.frameId)) return;519 if (payload.disposition === 'currentTab') this._page._frameManager.frameRequestedNavigation(payload.frameId);520 }521 _onFrameNavigatedWithinDocument(frameId, url) {522 if (this._eventBelongsToStaleFrame(frameId)) return;523 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);524 }525 _onFrameDetached(frameId, reason) {526 if (this._crPage._sessions.has(frameId)) {527 // This is a local -> remote frame transtion, where528 // Page.frameDetached arrives after Target.attachedToTarget.529 // We've already handled the new target and frame reattach - nothing to do here.530 return;531 }532 if (reason === 'swap') {533 // This is a local -> remote frame transtion, where534 // Page.frameDetached arrives before Target.attachedToTarget.535 // We should keep the frame in the tree, and it will be used for the new target.536 const frame = this._page._frameManager.frame(frameId);537 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);538 return;539 } // Just a regular frame detach.540 this._page._frameManager.frameDetached(frameId);541 }542 _onExecutionContextCreated(contextPayload) {543 const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;544 if (!frame || this._eventBelongsToStaleFrame(frame._id)) return;545 const delegate = new _crExecutionContext.CRExecutionContext(this._client, contextPayload);546 let worldName = null;547 if (contextPayload.auxData && !!contextPayload.auxData.isDefault) worldName = 'main';else if (contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';548 const context = new dom.FrameExecutionContext(delegate, frame, worldName);549 context[contextDelegateSymbol] = delegate;550 if (worldName) frame._contextCreated(worldName, context);551 this._contextIdToContext.set(contextPayload.id, context);552 }553 _onExecutionContextDestroyed(executionContextId) {554 const context = this._contextIdToContext.get(executionContextId);555 if (!context) return;556 this._contextIdToContext.delete(executionContextId);557 context.frame._contextDestroyed(context);558 }559 _onExecutionContextsCleared() {560 for (const contextId of Array.from(this._contextIdToContext.keys())) this._onExecutionContextDestroyed(contextId);561 }562 _onAttachedToTarget(event) {563 const session = _crConnection.CRConnection.fromSession(this._client).session(event.sessionId);564 if (event.targetInfo.type === 'iframe') {565 // Frame id equals target id.566 const targetId = event.targetInfo.targetId;567 const frame = this._page._frameManager.frame(targetId);568 if (!frame) return; // Subtree may be already gone due to renderer/browser race.569 this._page._frameManager.removeChildFramesRecursively(frame);570 const frameSession = new FrameSession(this._crPage, session, targetId, this);571 this._crPage._sessions.set(targetId, frameSession);572 frameSession._initialize(false).catch(e => e);573 return;574 }575 if (event.targetInfo.type !== 'worker') {576 // Ideally, detaching should resume any target, but there is a bug in the backend.577 session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {578 this._client._sendMayFail('Target.detachFromTarget', {579 sessionId: event.sessionId580 });581 });582 return;583 }584 const url = event.targetInfo.url;585 const worker = new _page.Worker(this._page, url);586 this._page._addWorker(event.sessionId, worker);587 session.once('Runtime.executionContextCreated', async event => {588 worker._createExecutionContext(new _crExecutionContext.CRExecutionContext(session, event.context));589 }); // This might fail if the target is closed before we initialize.590 session._sendMayFail('Runtime.enable');591 session._sendMayFail('Network.enable');592 session._sendMayFail('Runtime.runIfWaitingForDebugger');593 session.on('Runtime.consoleAPICalled', event => {594 const args = event.args.map(o => worker._existingExecutionContext.createHandle(o));595 this._page._addConsoleMessage(event.type, args, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));596 });597 session.on('Runtime.exceptionThrown', exception => this._page.emit(_page.Page.Events.PageError, (0, _crProtocolHelper.exceptionToError)(exception.exceptionDetails))); // TODO: attribute workers to the right frame.598 this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId));599 }600 _onDetachedFromTarget(event) {601 // This might be a worker...602 this._page._removeWorker(event.sessionId); // ... or an oopif.603 const childFrameSession = this._crPage._sessions.get(event.targetId);604 if (!childFrameSession) return; // Usually, we get frameAttached in this session first and mark child as swappedIn.605 if (childFrameSession._swappedIn) {606 childFrameSession.dispose();607 return;608 } // However, sometimes we get detachedFromTarget before frameAttached.609 // In this case we don't know wheter this is a remote frame detach,610 // or just a remote -> local transition. In the latter case, frameAttached611 // is already inflight, so let's make a safe roundtrip to ensure it arrives.612 this._client.send('Page.enable').catch(e => null).then(() => {613 // Child was not swapped in - that means frameAttached did not happen and614 // this is remote detach rather than remote -> local swap.615 if (!childFrameSession._swappedIn) this._page._frameManager.frameDetached(event.targetId);616 childFrameSession.dispose();617 });618 }619 _onWindowOpen(event) {620 this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);621 }622 async _onConsoleAPI(event) {623 if (event.executionContextId === 0) {624 // DevTools protocol stores the last 1000 console messages. These625 // messages are always reported even for removed execution contexts. In626 // this case, they are marked with executionContextId = 0 and are627 // reported upon enabling Runtime agent.628 //629 // Ignore these messages since:630 // - there's no execution context we can use to operate with message631 // arguments632 // - these messages are reported before Playwright clients can subscribe633 // to the 'console'634 // page event.635 //636 // @see https://github.com/GoogleChrome/puppeteer/issues/3865637 return;638 }639 const context = this._contextIdToContext.get(event.executionContextId);640 if (!context) return;641 const values = event.args.map(arg => context.createHandle(arg));642 this._page._addConsoleMessage(event.type, values, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));643 }644 async _initBinding(binding) {645 await Promise.all([this._client.send('Runtime.addBinding', {646 name: binding.name647 }), this._client.send('Page.addScriptToEvaluateOnNewDocument', {648 source: binding.source649 })]);650 }651 async _onBindingCalled(event) {652 const pageOrError = await this._crPage.pageOrError();653 if (!(pageOrError instanceof Error)) {654 const context = this._contextIdToContext.get(event.executionContextId);655 if (context) await this._page._onBindingCalled(event.payload, context);656 }657 }658 _onDialog(event) {659 if (!this._page._frameManager.frame(this._targetId)) return; // Our frame/subtree may be gone already.660 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {661 await this._client.send('Page.handleJavaScriptDialog', {662 accept,663 promptText664 });665 }, event.defaultPrompt));666 }667 _handleException(exceptionDetails) {668 this._page.firePageError((0, _crProtocolHelper.exceptionToError)(exceptionDetails));669 }670 async _onTargetCrashed() {671 this._client._markAsCrashed();672 this._page._didCrash();673 }674 _onLogEntryAdded(event) {675 const {676 level,677 text,678 args,679 source,680 url,681 lineNumber682 } = event.entry;683 if (args) args.map(arg => (0, _crProtocolHelper.releaseObject)(this._client, arg.objectId));684 if (source !== 'worker') {685 const location = {686 url: url || '',687 lineNumber: lineNumber || 0,688 columnNumber: 0689 };690 this._page._addConsoleMessage(level, [], location, text);691 }692 }693 async _onFileChooserOpened(event) {694 const frame = this._page._frameManager.frame(event.frameId);695 if (!frame) return;696 let handle;697 try {698 const utilityContext = await frame._utilityContext();699 handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);700 } catch (e) {701 // During async processing, frame/context may go away. We should not throw.702 return;703 }704 await this._page._onFileChooserOpened(handle);705 }706 _willBeginDownload() {707 const originPage = this._crPage._initializedPage;708 if (!originPage) {709 // Resume the page creation with an error. The page will automatically close right710 // after the download begins.711 this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));712 }713 }714 _onScreencastFrame(payload) {715 this._page.throttleScreencastFrameAck(() => {716 this._client.send('Page.screencastFrameAck', {717 sessionId: payload.sessionId718 }).catch(() => {});719 });720 const buffer = Buffer.from(payload.data, 'base64');721 this._page.emit(_page.Page.Events.ScreencastFrame, {722 buffer,723 timestamp: payload.metadata.timestamp,724 width: payload.metadata.deviceWidth,725 height: payload.metadata.deviceHeight726 });727 }728 async _createVideoRecorder(screencastId, options) {729 (0, _utils.assert)(!this._screencastId);730 const ffmpegPath = _registry.registry.findExecutable('ffmpeg').executablePathOrDie(this._page._browserContext._browser.options.sdkLanguage);731 this._videoRecorder = await _videoRecorder.VideoRecorder.launch(this._crPage._page, ffmpegPath, options);732 this._screencastId = screencastId;733 }734 async _startVideoRecording(options) {735 const screencastId = this._screencastId;736 (0, _utils.assert)(screencastId);737 this._page.once(_page.Page.Events.Close, () => this._stopVideoRecording().catch(() => {}));738 const gotFirstFrame = new Promise(f => this._client.once('Page.screencastFrame', f));739 await this._startScreencast(this._videoRecorder, {740 format: 'jpeg',741 quality: 90,742 maxWidth: options.width,743 maxHeight: options.height744 }); // Wait for the first frame before reporting video to the client.745 gotFirstFrame.then(() => {746 this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());747 });748 }749 async _stopVideoRecording() {750 if (!this._screencastId) return;751 const screencastId = this._screencastId;752 this._screencastId = null;753 const recorder = this._videoRecorder;754 this._videoRecorder = null;755 await this._stopScreencast(recorder);756 await recorder.stop().catch(() => {}); // Keep the video artifact in the map utntil encoding is fully finished, if the context757 // starts closing before the video is fully written to disk it will wait for it.758 const video = this._crPage._browserContext._browser._takeVideo(screencastId);759 video === null || video === void 0 ? void 0 : video.reportFinished();760 }761 async _startScreencast(client, options = {}) {762 this._screencastClients.add(client);763 if (this._screencastClients.size === 1) await this._client.send('Page.startScreencast', options);...
TargetRegistry.js
Source:TargetRegistry.js
...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':837 return new Dialog(prompt, 'prompt');838 case 'confirm':...
ViroARSceneNavigator.js
Source:ViroARSceneNavigator.js
...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.373 */374 async _takeScreenshot(fileName, saveToCameraRoll) {375 return await ViroARSceneNavigatorModule.takeScreenshot(findNodeHandle(this), fileName, saveToCameraRoll);376 },377 async _project(point) {378 return await ViroARSceneNavigatorModule.project(findNodeHandle(this), point);379 },...
ARSceneNavigator.js
Source:ARSceneNavigator.js
...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.373 */374 async _takeScreenshot(fileName, saveToCameraRoll) {375 return await ARSceneNavigatorModule.takeScreenshot(findNodeHandle(this), fileName, saveToCameraRoll);376 },377 async _project(point) {378 return await ARSceneNavigatorModule.project(findNodeHandle(this), point);379 },...
main.js
Source:main.js
...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");194 signOut();195 }196 });...
videoCapture.js
Source:videoCapture.js
...26 }27 });28 this.mediaRecorder.start(10);29 }30 _stopVideoRecording(e){31 try{32 this.mediaRecorder.stop();33 this.mediaRecorder = null;34 this.stream = null;35 let now = new Date();36 let foldername = now.toDateString()+'/videostream/';37 let filename = now.toTimeString()+".webm";38 let name = foldername + filename;39 uploadData(name, this.recordedBlobs, "video/webm");40 } catch(e) {41 // handle error42 }43 }44}
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Start Recording');7 await page.click('text=Stop Recording');8 await browser.close();9})();10 at CDPSession.send (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\cdp.js:130:19)11 at Page._startScreencast (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\page.js:2208:37)12 at Page.startScreencast (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\page.js:2182:21)13 at Page._startVideoRecording (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\page.js:2256:10)14 at Page.startVideoRecording (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\page.js:2248:21)15 at Page.click (C:\Users\user\Desktop\Playwright\playwright\node_modules\playwright\lib\page.js:2675:10)16 at Object.<anonymous> (C:\Users\user\Desktop\Playwright\playwright\test.js:8:10)17 at Module._compile (internal/modules/cjs/loader.js:1063:30)18 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)19 at Module.load (internal/modules/cjs/loader.js:928:32)
Using AI Code Generation
1const {chromium} = require('playwright');2const path = require('path');3(async () => {4 const browser = await chromium.launch({headless: false});5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Play');8 await page.waitForTimeout(10000);9 const video = await page.video();10 const videoPath = path.join(__dirname, 'video.mp4');11 await video._stopVideoRecording(videoPath);12 await browser.close();13})();14{15 "scripts": {16 },17 "dependencies": {18 }19}20_stopVideoRecording(options)21await video._stopVideoRecording({path: 'video.mp4', timeout: 10000});
Using AI Code Generation
1const {chromium} = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch({headless: false});6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.click('text=Play');9 await page.waitForTimeout(10000);10 const video = await page._stopVideoRecording();11 await video.saveAs(path.join(__dirname, 'video.webm'));12 await browser.close();13})();14{15 "scripts": {16 },17 "dependencies": {18 }19}20{21 "packages": {22 "": {23 "dependencies": {24 },25 "devDependencies": {26 }27 },28 "node_modules/playwright": {29 "dependencies": {
Using AI Code Generation
1const { _stopVideoRecording } = require('playwright/lib/utils/recorderUtils');2const { _startVideoRecording } = require('playwright/lib/utils/recorderUtils');3const { _stopVideoRecording } = require('playwright/lib/utils/recorderUtils');4const { _startVideoRecording } = require('playwright/lib/utils/recorderUtils');5(async () => {6 const browser = await chromium.launch({ headless: false });7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.fill('input[name="q"]', 'Playwright');10 await page.press('input[name="q"]', 'Enter');11 await page.click('text=Playwright');12 await page.waitForLoadState('networkidle');13 await browser.close();14})();15const { _stopVideoRecording } = require('playwright/lib/utils/recorderUtils');16const { _startVideoRecording } = require('playwright/lib/utils/recorderUtils');17(async () => {18 const browser = await chromium.launch({ headless: false });19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.fill('input[name="q"]', 'Playwright');22 await page.press('input[name="q"]', 'Enter');23 await page.click('text=Playwright');24 await page.waitForLoadState('networkidle');25 await browser.close();26})();27const { _stopVideoRecording } = require('playwright/lib/utils/recorderUtils');28const { _startVideoRecording } = require('playwright/lib/utils/recorderUtils');29(async () => {30 const browser = await chromium.launch({ headless: false });31 const context = await browser.newContext();32 const page = await context.newPage();
Using AI Code Generation
1const { _stopVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');2const { _startVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');3const { _createRecorderApp } = require('playwright/lib/server/chromium/recorder/recorderApp');4const { chromium } = require('playwright');5const { _createRecorderApp } = require('playwright/lib/server/chromium/recorder/recorderApp');6const { _startVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');7(async () => {8 const browser = await chromium.launch();9 const context = await browser.newContext();10 const page = await context.newPage();11 await _startVideoRecording(page, { fps: 30, path: 'test.mp4' });12 await _stopVideoRecording(page);13 await browser.close();14})();15const { _stopVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');16const { _startVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');17const { _createRecorderApp } = require('playwright/lib/server/chromium/recorder/recorderApp');18const { chromium } = require('playwright');19const { _createRecorderApp } = require('playwright/lib/server/chromium/recorder/recorderApp');20const { _startVideoRecording } = require('playwright/lib/server/chromium/recorder/recorderApp');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await _startVideoRecording(page, {
Using AI Code Generation
1const { _stopVideoRecording } = require('playwright');2const browser = await chromium.launch({ headless: false });3const context = await browser.newContext();4const page = await context.newPage();5await _stopVideoRecording(page);6await browser.close();7const { _startVideoRecording } = require('playwright');8const browser = await chromium.launch({ headless: false });9const context = await browser.newContext();10const page = await context.newPage();11await _startVideoRecording(page, {12 size: {13 },14});15await browser.close();16const { _deleteVideoRecording } = require('playwright');17const browser = await chromium.launch({ headless: false });18const context = await browser.newContext();19const page = await context.newPage();20await _deleteVideoRecording(page);21await browser.close();22const { _startTracing } = require('playwright');23const browser = await chromium.launch({ headless: false });24const context = await browser.newContext();25const page = await context.newPage();26await _startTracing(page, {27});28await browser.close();29const { _stopTracing } = require('playwright');30const browser = await chromium.launch({ headless: false });31const context = await browser.newContext();32const page = await context.newPage();33await _stopTracing(page, 'trace.zip');34await browser.close();35const { _deleteTracing } = require('playwright');36const browser = await chromium.launch({ headless: false });37const context = await browser.newContext();38const page = await context.newPage();39await _deleteTracing(page);40await browser.close();41const { _startRecordingScreen } = require('playwright');42const browser = await chromium.launch({ headless: false });43const context = await browser.newContext();
Using AI Code Generation
1const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');2const browser = await chromium.launch();3const page = await browser.newPage();4const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');5const browser = await chromium.launch();6const page = await browser.newPage();7const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');8const browser = await chromium.launch();9const page = await browser.newPage();10const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');11const browser = await chromium.launch();12const page = await browser.newPage();13const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');14const browser = await chromium.launch();15const page = await browser.newPage();16const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');17const browser = await chromium.launch();18const page = await browser.newPage();
Using AI Code Generation
1const { _stopVideoRecording } = require('playwright/lib/server/chromium/crBrowser');2const browser = await chromium.launch();3const context = await browser.newContext();4const page = await context.newPage();5await page._startVideoRecording();6await _stopVideoRecording(page);7await browser.close();
Using AI Code Generation
1const { _stopVideoRecording } = require('@playwright/test/lib/server/video/recorder');2const video = await page.video();3await _stopVideoRecording(video, 'test.mp4');4const { _startVideoRecording } = require('@playwright/test/lib/server/video/recorder');5await _startVideoRecording(page, 'test.mp4');6const { _deleteVideo } = require('@playwright/test/lib/server/video/recorder');7const video = await page.video();8await _deleteVideo(video);9const { _downloadVideo } = require('@playwright/test/lib/server/video/recorder');10const video = await page.video();11await _downloadVideo(video);
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!!