Best JavaScript code snippet using playwright-internal
page.js
Source:page.js
...457 this._pageBindings.get(name) ||458 this._browserContext._pageBindings.get(name)459 )460 }461 setScreencastOptions(options) {462 this._delegate463 .setScreencastOptions(options)464 .catch((e) => _debugLogger.debugLogger.log('error', e))465 this._frameThrottler.setEnabled(!!options)466 }467 throttleScreencastFrameAck(ack) {468 // Don't ack immediately, tracing has smart throttling logic that is implemented here.469 this._frameThrottler.ack(ack)470 }471 temporarlyDisableTracingScreencastThrottling() {472 this._frameThrottler.recharge()473 }474 firePageError(error) {475 this.emit(Page.Events.PageError, error)476 }477 parseSelector(selector, options) {...
tracing.js
Source:tracing.js
...115 this._screencastListeners.push(_eventsHelper.eventsHelper.addEventListener(this._context, _browserContext.BrowserContext.Events.Page, this._startScreencastInPage.bind(this)));116 }117 _stopScreencast() {118 _eventsHelper.eventsHelper.removeEventListeners(this._screencastListeners);119 for (const page of this._context.pages()) page.setScreencastOptions(null);120 }121 async stop() {122 if (!this._state) return;123 if (this._isStopping) throw new Error(`Tracing is already stopping`);124 if (this._state.recording) throw new Error(`Must stop trace file before stopping tracing`);125 this._harTracer.stop();126 await this._writeChain;127 this._state = undefined;128 }129 async dispose() {130 this._snapshotter.dispose();131 await this._writeChain;132 }133 async stopChunk(save) {134 if (this._isStopping) throw new Error(`Tracing is already stopping`);135 this._isStopping = true;136 for (const {137 sdkObject,138 metadata,139 beforeSnapshot,140 actionSnapshot,141 afterSnapshot142 } of this._pendingCalls.values()) {143 await Promise.all([beforeSnapshot, actionSnapshot, afterSnapshot]);144 let callMetadata = metadata;145 if (!afterSnapshot) {146 // Note: we should not modify metadata here to avoid side-effects in any other place.147 callMetadata = { ...metadata,148 error: {149 error: {150 name: 'Error',151 message: 'Action was interrupted'152 }153 }154 };155 }156 await this.onAfterCall(sdkObject, callMetadata);157 }158 if (!this._state || !this._state.recording) {159 this._isStopping = false;160 if (save) throw new Error(`Must start tracing before stopping`);161 return null;162 }163 const state = this._state;164 this._context.instrumentation.removeListener(this);165 if (state.options.screenshots) this._stopScreencast();166 if (state.options.snapshots) await this._snapshotter.stop(); // Chain the export operation against write operations,167 // so that neither trace files nor sha1s change during the export.168 return await this._appendTraceOperation(async () => {169 const result = save ? this._export(state) : Promise.resolve(null);170 return result.finally(async () => {171 this._isStopping = false;172 state.recording = false;173 });174 });175 }176 async _export(state) {177 const zipFile = new _yazl.default.ZipFile();178 const failedPromise = new Promise((_, reject) => zipFile.on('error', reject));179 const succeededPromise = new Promise(fulfill => {180 zipFile.addFile(state.traceFile, 'trace.trace');181 zipFile.addFile(state.networkFile, 'trace.network');182 const zipFileName = state.traceFile + '.zip';183 for (const sha1 of state.sha1s) zipFile.addFile(_path.default.join(this._resourcesDir, sha1), _path.default.join('resources', sha1));184 zipFile.end();185 zipFile.outputStream.pipe(_fs.default.createWriteStream(zipFileName)).on('close', () => {186 const artifact = new _artifact.Artifact(this._context, zipFileName);187 artifact.reportFinished();188 fulfill(artifact);189 });190 });191 return Promise.race([failedPromise, succeededPromise]);192 }193 async _captureSnapshot(name, sdkObject, metadata, element) {194 if (!sdkObject.attribution.page) return;195 if (!this._snapshotter.started()) return;196 if (!shouldCaptureSnapshot(metadata)) return;197 const snapshotName = `${name}@${metadata.id}`;198 metadata.snapshots.push({199 title: name,200 snapshotName201 }); // We have |element| for input actions (page.click and handle.click)202 // and |sdkObject| element for accessors like handle.textContent.203 if (!element && sdkObject instanceof _dom.ElementHandle) element = sdkObject;204 await this._snapshotter.captureSnapshot(sdkObject.attribution.page, snapshotName, element).catch(() => {});205 }206 async onBeforeCall(sdkObject, metadata) {207 // Set afterSnapshot name for all the actions that operate selectors.208 // Elements resolved from selectors will be marked on the snapshot.209 metadata.afterSnapshot = `after@${metadata.id}`;210 const beforeSnapshot = this._captureSnapshot('before', sdkObject, metadata);211 this._pendingCalls.set(metadata.id, {212 sdkObject,213 metadata,214 beforeSnapshot215 });216 await beforeSnapshot;217 }218 async onBeforeInputAction(sdkObject, metadata, element) {219 const actionSnapshot = this._captureSnapshot('action', sdkObject, metadata, element);220 this._pendingCalls.get(metadata.id).actionSnapshot = actionSnapshot;221 await actionSnapshot;222 }223 async onAfterCall(sdkObject, metadata) {224 const pendingCall = this._pendingCalls.get(metadata.id);225 if (!pendingCall || pendingCall.afterSnapshot) return;226 if (!sdkObject.attribution.context) {227 this._pendingCalls.delete(metadata.id);228 return;229 }230 pendingCall.afterSnapshot = this._captureSnapshot('after', sdkObject, metadata);231 await pendingCall.afterSnapshot;232 const event = {233 type: 'action',234 metadata235 };236 this._appendTraceEvent(event);237 this._pendingCalls.delete(metadata.id);238 }239 onEvent(sdkObject, metadata) {240 if (!sdkObject.attribution.context) return;241 const event = {242 type: 'event',243 metadata244 };245 this._appendTraceEvent(event);246 }247 onEntryStarted(entry) {}248 onEntryFinished(entry) {249 const event = {250 type: 'resource-snapshot',251 snapshot: entry252 };253 this._appendTraceOperation(async () => {254 visitSha1s(event, this._state.sha1s);255 await _fs.default.promises.appendFile(this._state.networkFile, JSON.stringify(event) + '\n');256 });257 }258 onContentBlob(sha1, buffer) {259 this._appendResource(sha1, buffer);260 }261 onSnapshotterBlob(blob) {262 this._appendResource(blob.sha1, blob.buffer);263 }264 onFrameSnapshot(snapshot) {265 this._appendTraceEvent({266 type: 'frame-snapshot',267 snapshot268 });269 }270 _startScreencastInPage(page) {271 page.setScreencastOptions(kScreencastOptions);272 const prefix = page.guid;273 let frameSeq = 0;274 this._screencastListeners.push(_eventsHelper.eventsHelper.addEventListener(page, _page.Page.Events.ScreencastFrame, params => {275 const suffix = String(++frameSeq).padStart(10, '0');276 const sha1 = `${prefix}-${suffix}.jpeg`;277 const event = {278 type: 'screencast-frame',279 pageId: page.guid,280 sha1,281 width: params.width,282 height: params.height,283 timestamp: (0, _utils.monotonicTime)()284 }; // Make sure to write the screencast frame before adding a reference to it.285 this._appendResource(sha1, params.buffer);...
BrowserHandler.js
Source:BrowserHandler.js
...167 async ['Browser.setColorScheme']({browserContextId, colorScheme}) {168 await this._targetRegistry.browserContextForId(browserContextId).setColorScheme(nullToUndefined(colorScheme));169 }170 async ['Browser.setScreencastOptions']({browserContextId, dir, width, height, scale}) {171 await this._targetRegistry.browserContextForId(browserContextId).setScreencastOptions({dir, width, height, scale});172 }173 async ['Browser.setUserAgentOverride']({browserContextId, userAgent}) {174 await this._targetRegistry.browserContextForId(browserContextId).setDefaultUserAgent(userAgent);175 }176 async ['Browser.setBypassCSP']({browserContextId, bypassCSP}) {177 await this._targetRegistry.browserContextForId(browserContextId).applySetting('bypassCSP', nullToUndefined(bypassCSP));178 }179 async ['Browser.setJavaScriptDisabled']({browserContextId, javaScriptDisabled}) {180 await this._targetRegistry.browserContextForId(browserContextId).applySetting('javaScriptDisabled', nullToUndefined(javaScriptDisabled));181 }182 async ['Browser.setLocaleOverride']({browserContextId, locale}) {183 await this._targetRegistry.browserContextForId(browserContextId).applySetting('locale', nullToUndefined(locale));184 }185 async ['Browser.setTimezoneOverride']({browserContextId, timezoneId}) {...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const client = await page.context().newCDPSession(page);7 await client.send('Emulation.setScreencastOptions', {8 });9 await page.screenshot({ path: 'google.png' });10 await browser.close();11})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9module.exports = {10 use: {11 launchOptions: {12 },13 contextOptions: {14 recordVideo: { dir: 'videos/' },15 recordTrace: { dir: 'traces/' },16 recordScreenshots: { dir: 'screenshots/' },17 },18 },19};20{21 "scripts": {22 },23 "devDependencies": {24 }25}26{27 "scripts": {28 },29 "devDependencies": {30 },31 "playwright": {32 "use": {
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.setScreencastOptions({width: 800, height: 600, quality: 80});7 await page.screencastFrameAck(1);8 await browser.close();9})();10Recommended Posts: Playwright | setViewportSize() Method11Playwright | setViewportSize() Method12Playwright | setExtraHTTPHeaders() Method13Playwright | setGeolocation() Method14Playwright | setOffline() Method15Playwright | setDefaultTimeout() Method
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page._client.send('Emulation.setScreencastOptions', {7 });8 await page.screenshot({path: 'google.png'});9 await browser.close();10})();
Using AI Code Generation
1const playwright = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await playwright.chromium.launch({5 });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'google.png' });9 await page._client.send('Page.setScreencastOptions', {10 });11 await page.screenshot({12 clip: { x: 0, y: 0, width: 1280, height: 720 },13 });14 await browser.close();15})();16Hi @dgozman, I am also facing the same issue. I have a test which is failing because of the screenshot. I tried the workaround by setting the format to jpeg but the issue still persists. I am using the latest version of Playwright (1.11.1). Can you please help me with this?17const page = await context.newPage();18await page.screenshot({ path: 'google.png' });19await page._client.send('Page.setScreencastOptions', {20});21await page.screenshot({22 clip: { x: 0, y: 0, width: 1280, height: 720 },23});24const page = await context.newPage();25await page.screenshot({ path: 'google.png' });
Using AI Code Generation
1const playwright = require('playwright');2const { setScreencastOptions } = require('playwright/lib/server/supplements/recorder/recorderSupplement');3(async () => {4 const browser = await playwright.chromium.launch({ headless: false });5 const context = await browser.newContext();6 await setScreencastOptions(context, { width: 1280, height: 720, outputDir: '/tmp/videos' });7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();11const { setScreencastOptions } = require('playwright/lib/server/supplements/recorder/recorderSupplement');12module.exports = {13 use: {14 viewport: { width: 1280, height: 720 },15 launchOptions: { args: ['--no-sandbox', '--disable-setuid-sandbox'], },16 contextOptions: { recordVideo: { dir: '/tmp/videos' } },17 },18 {19 use: {20 viewport: { width: 1280, height: 720 },21 launchOptions: { args: ['--no-sandbox', '--disable-setuid-sandbox'], },22 },23 },24 {25 use: {26 viewport: { width: 1280, height: 720 },27 launchOptions: { args: ['--no-sandbox', '--disable-setuid-sandbox'], },28 },29 },30 {31 use: {32 viewport: { width: 1280, height: 720 },33 launchOptions: { args: ['--no-sandbox', '--disable-setuid-sandbox'], },34 },35 },36 {
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!!