Best JavaScript code snippet using playwright-internal
wkPage.js
Source:wkPage.js
...178 width: this._page._state.emulatedSize.screen.width,179 height: this._page._state.emulatedSize.screen.height180 }));181 }182 promises.push(this.updateEmulateMedia());183 promises.push(session.send('Network.setExtraHTTPHeaders', {184 headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false185 /* lowerCase */186 )187 }));188 if (contextOptions.offline) promises.push(session.send('Network.setEmulateOfflineState', {189 offline: true190 }));191 promises.push(session.send('Page.setTouchEmulationEnabled', {192 enabled: !!contextOptions.hasTouch193 }));194 if (contextOptions.timezoneId) {195 promises.push(session.send('Page.setTimeZone', {196 timeZone: contextOptions.timezoneId197 }).catch(e => {198 throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`);199 }));200 }201 promises.push(session.send('Page.overrideSetting', {202 setting: 'DeviceOrientationEventEnabled',203 value: contextOptions.isMobile204 }));205 promises.push(session.send('Page.overrideSetting', {206 setting: 'FullScreenEnabled',207 value: !contextOptions.isMobile208 }));209 promises.push(session.send('Page.overrideSetting', {210 setting: 'NotificationsEnabled',211 value: !contextOptions.isMobile212 }));213 promises.push(session.send('Page.overrideSetting', {214 setting: 'PointerLockEnabled',215 value: !contextOptions.isMobile216 }));217 promises.push(session.send('Page.overrideSetting', {218 setting: 'InputTypeMonthEnabled',219 value: contextOptions.isMobile220 }));221 promises.push(session.send('Page.overrideSetting', {222 setting: 'InputTypeWeekEnabled',223 value: contextOptions.isMobile224 }));225 await Promise.all(promises);226 }227 _onDidCommitProvisionalTarget(event) {228 const {229 oldTargetId,230 newTargetId231 } = event;232 (0, _utils.assert)(this._provisionalPage);233 (0, _utils.assert)(this._provisionalPage._session.sessionId === newTargetId, 'Unknown new target: ' + newTargetId);234 (0, _utils.assert)(this._session.sessionId === oldTargetId, 'Unknown old target: ' + oldTargetId);235 const newSession = this._provisionalPage._session;236 this._provisionalPage.commit();237 this._provisionalPage.dispose();238 this._provisionalPage = null;239 this._setSession(newSession);240 }241 _onTargetDestroyed(event) {242 const {243 targetId,244 crashed245 } = event;246 if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) {247 this._provisionalPage._session.dispose(false);248 this._provisionalPage.dispose();249 this._provisionalPage = null;250 } else if (this._session.sessionId === targetId) {251 this._session.dispose(false);252 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);253 if (crashed) {254 this._session.markAsCrashed();255 this._page._didCrash();256 }257 }258 }259 didClose() {260 this._page._didClose();261 }262 dispose(disconnected) {263 this._pageProxySession.dispose(disconnected);264 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);265 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);266 if (this._session) this._session.dispose(disconnected);267 if (this._provisionalPage) {268 this._provisionalPage._session.dispose(disconnected);269 this._provisionalPage.dispose();270 this._provisionalPage = null;271 }272 this._page._didDisconnect();273 this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));274 }275 dispatchMessageToSession(message) {276 this._pageProxySession.dispatchMessage(message);277 }278 handleProvisionalLoadFailed(event) {279 if (!this._initializedPage) {280 this._firstNonInitialNavigationCommittedReject(new Error('Initial load failed'));281 return;282 }283 if (!this._provisionalPage) return;284 let errorText = event.error;285 if (errorText.includes('cancelled')) errorText += '; maybe frame was detached?';286 this._page._frameManager.frameAbortedNavigation(this._page.mainFrame()._id, errorText, event.loaderId);287 }288 handleWindowOpen(event) {289 (0, _utils.debugAssert)(!this._nextWindowOpenPopupFeatures);290 this._nextWindowOpenPopupFeatures = event.windowFeatures;291 }292 async pageOrError() {293 return this._pagePromise;294 }295 async _onTargetCreated(event) {296 const {297 targetInfo298 } = event;299 const session = new _wkConnection.WKSession(this._pageProxySession.connection, targetInfo.targetId, `Target closed`, message => {300 this._pageProxySession.send('Target.sendMessageToTarget', {301 message: JSON.stringify(message),302 targetId: targetInfo.targetId303 }).catch(e => {304 session.dispatchMessage({305 id: message.id,306 error: {307 message: e.message308 }309 });310 });311 });312 (0, _utils.assert)(targetInfo.type === 'page', 'Only page targets are expected in WebKit, received: ' + targetInfo.type);313 if (!targetInfo.isProvisional) {314 (0, _utils.assert)(!this._initializedPage);315 let pageOrError;316 try {317 this._setSession(session);318 await Promise.all([this._initializePageProxySession(), this._initializeSession(session, false, ({319 frameTree320 }) => this._handleFrameTree(frameTree))]);321 pageOrError = this._page;322 } catch (e) {323 pageOrError = e;324 }325 if (targetInfo.isPaused) this._pageProxySession.sendMayFail('Target.resume', {326 targetId: targetInfo.targetId327 });328 if (pageOrError instanceof _page.Page && this._page.mainFrame().url() === '') {329 try {330 // Initial empty page has an empty url. We should wait until the first real url has been loaded,331 // even if that url is about:blank. This is especially important for popups, where we need the332 // actual url before interacting with it.333 await this._firstNonInitialNavigationCommittedPromise;334 } catch (e) {335 pageOrError = e;336 }337 } else {338 // Avoid rejection on disconnect.339 this._firstNonInitialNavigationCommittedPromise.catch(() => {});340 }341 await this._page.initOpener(this._opener); // Note: it is important to call |reportAsNew| before resolving pageOrError promise,342 // so that anyone who awaits pageOrError got a ready and reported page.343 this._initializedPage = pageOrError instanceof _page.Page ? pageOrError : null;344 this._page.reportAsNew(pageOrError instanceof _page.Page ? undefined : pageOrError);345 this._pagePromise.resolve(pageOrError);346 } else {347 (0, _utils.assert)(targetInfo.isProvisional);348 (0, _utils.assert)(!this._provisionalPage);349 this._provisionalPage = new _wkProvisionalPage.WKProvisionalPage(session, this);350 if (targetInfo.isPaused) {351 this._provisionalPage.initializationPromise.then(() => {352 this._pageProxySession.sendMayFail('Target.resume', {353 targetId: targetInfo.targetId354 });355 });356 }357 }358 }359 _onDispatchMessageFromTarget(event) {360 const {361 targetId,362 message363 } = event;364 if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) this._provisionalPage._session.dispatchMessage(JSON.parse(message));else if (this._session.sessionId === targetId) this._session.dispatchMessage(JSON.parse(message));else throw new Error('Unknown target: ' + targetId);365 }366 _addSessionListeners() {367 // TODO: remove Page.willRequestOpenWindow and Page.didRequestOpenWindow from the protocol.368 this._sessionListeners = [_eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameScheduledNavigation', event => this._onFrameScheduledNavigation(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.loadEventFired', event => this._onLifecycleEvent(event.frameId, 'load')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.domContentEventFired', event => this._onLifecycleEvent(event.frameId, 'domcontentloaded')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageAdded', event => this._onConsoleMessage(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageRepeatCountUpdated', event => this._onConsoleRepeatCountUpdated(event)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Dialog.javascriptDialogOpening', event => this._onDialog(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestWillBeSent', e => this._onRequestWillBeSent(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestIntercepted', e => this._onRequestIntercepted(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.responseReceived', e => this._onResponseReceived(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFinished', e => this._onLoadingFinished(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFailed', e => this._onLoadingFailed(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage))];369 }370 async _updateState(method, params) {371 await this._forAllSessions(session => session.send(method, params).then());372 }373 async _forAllSessions(callback) {374 const sessions = [this._session]; // If the state changes during provisional load, push it to the provisional page375 // as well to always be in sync with the backend.376 if (this._provisionalPage) sessions.push(this._provisionalPage._session);377 await Promise.all(sessions.map(session => callback(session).catch(e => {})));378 }379 _onFrameScheduledNavigation(frameId) {380 this._page._frameManager.frameRequestedNavigation(frameId);381 }382 _onFrameStoppedLoading(frameId) {383 this._page._frameManager.frameStoppedLoading(frameId);384 }385 _onLifecycleEvent(frameId, event) {386 this._page._frameManager.frameLifecycleEvent(frameId, event);387 }388 _handleFrameTree(frameTree) {389 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);390 this._onFrameNavigated(frameTree.frame, true);391 this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'domcontentloaded');392 this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'load');393 if (!frameTree.childFrames) return;394 for (const child of frameTree.childFrames) this._handleFrameTree(child);395 }396 _onFrameAttached(frameId, parentFrameId) {397 return this._page._frameManager.frameAttached(frameId, parentFrameId);398 }399 _onFrameNavigated(framePayload, initial) {400 const frame = this._page._frameManager.frame(framePayload.id);401 (0, _utils.assert)(frame);402 this._removeContextsForFrame(frame, true);403 if (!framePayload.parentId) this._workers.clear();404 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial);405 if (!initial) this._firstNonInitialNavigationCommittedFulfill();406 }407 _onFrameNavigatedWithinDocument(frameId, url) {408 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);409 }410 _onFrameDetached(frameId) {411 this._page._frameManager.frameDetached(frameId);412 }413 _removeContextsForFrame(frame, notifyFrame) {414 for (const [contextId, context] of this._contextIdToContext) {415 if (context.frame === frame) {416 this._contextIdToContext.delete(contextId);417 if (notifyFrame) frame._contextDestroyed(context);418 }419 }420 }421 _onExecutionContextCreated(contextPayload) {422 if (this._contextIdToContext.has(contextPayload.id)) return;423 const frame = this._page._frameManager.frame(contextPayload.frameId);424 if (!frame) return;425 const delegate = new _wkExecutionContext.WKExecutionContext(this._session, contextPayload.id);426 let worldName = null;427 if (contextPayload.type === 'normal') worldName = 'main';else if (contextPayload.type === 'user' && contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';428 const context = new dom.FrameExecutionContext(delegate, frame, worldName);429 context[contextDelegateSymbol] = delegate;430 if (worldName) frame._contextCreated(worldName, context);431 if (contextPayload.type === 'normal' && frame === this._page.mainFrame()) this._mainFrameContextId = contextPayload.id;432 this._contextIdToContext.set(contextPayload.id, context);433 }434 async navigateFrame(frame, url, referrer) {435 if (this._pageProxySession.isDisposed()) throw new Error('Target closed');436 const pageProxyId = this._pageProxySession.sessionId;437 const result = await this._pageProxySession.connection.browserSession.send('Playwright.navigate', {438 url,439 pageProxyId,440 frameId: frame._id,441 referrer442 });443 return {444 newDocumentId: result.loaderId445 };446 }447 _onConsoleMessage(event) {448 // Note: do no introduce await in this function, otherwise we lose the ordering.449 // For example, frame.setContent relies on this.450 const {451 type,452 level,453 text,454 parameters,455 url,456 line: lineNumber,457 column: columnNumber,458 source459 } = event.message;460 if (level === 'debug' && parameters && parameters[0].value === BINDING_CALL_MESSAGE) {461 const parsedObjectId = JSON.parse(parameters[1].objectId);462 this.pageOrError().then(pageOrError => {463 const context = this._contextIdToContext.get(parsedObjectId.injectedScriptId);464 if (!(pageOrError instanceof Error) && context) this._page._onBindingCalled(parameters[2].value, context);465 });466 return;467 }468 if (level === 'error' && source === 'javascript') {469 const {470 name,471 message472 } = (0, _stackTrace.splitErrorMessage)(text);473 let stack;474 if (event.message.stackTrace) {475 stack = text + '\n' + event.message.stackTrace.map(callFrame => {476 return ` at ${callFrame.functionName || 'unknown'} (${callFrame.url}:${callFrame.lineNumber}:${callFrame.columnNumber})`;477 }).join('\n');478 } else {479 stack = '';480 }481 const error = new Error(message);482 error.stack = stack;483 error.name = name;484 this._page.firePageError(error);485 return;486 }487 let derivedType = type || '';488 if (type === 'log') derivedType = level;else if (type === 'timing') derivedType = 'timeEnd';489 const handles = [];490 for (const p of parameters || []) {491 let context;492 if (p.objectId) {493 const objectId = JSON.parse(p.objectId);494 context = this._contextIdToContext.get(objectId.injectedScriptId);495 } else {496 context = this._contextIdToContext.get(this._mainFrameContextId);497 }498 if (!context) return;499 handles.push(context.createHandle(p));500 }501 this._lastConsoleMessage = {502 derivedType,503 text,504 handles,505 count: 0,506 location: {507 url: url || '',508 lineNumber: (lineNumber || 1) - 1,509 columnNumber: (columnNumber || 1) - 1510 }511 };512 this._onConsoleRepeatCountUpdated({513 count: 1514 });515 }516 _onConsoleRepeatCountUpdated(event) {517 if (this._lastConsoleMessage) {518 const {519 derivedType,520 text,521 handles,522 count,523 location524 } = this._lastConsoleMessage;525 for (let i = count; i < event.count; ++i) this._page._addConsoleMessage(derivedType, handles, location, handles.length ? undefined : text);526 this._lastConsoleMessage.count = event.count;527 }528 }529 _onDialog(event) {530 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {531 await this._pageProxySession.send('Dialog.handleJavaScriptDialog', {532 accept,533 promptText534 });535 }, event.defaultPrompt));536 }537 async _onFileChooserOpened(event) {538 let handle;539 try {540 const context = await this._page._frameManager.frame(event.frameId)._mainContext();541 handle = context.createHandle(event.element).asElement();542 } catch (e) {543 // During async processing, frame/context may go away. We should not throw.544 return;545 }546 await this._page._onFileChooserOpened(handle);547 }548 static async _setEmulateMedia(session, mediaType, colorScheme, reducedMotion) {549 const promises = [];550 promises.push(session.send('Page.setEmulatedMedia', {551 media: mediaType || ''552 }));553 let appearance = undefined;554 switch (colorScheme) {555 case 'light':556 appearance = 'Light';557 break;558 case 'dark':559 appearance = 'Dark';560 break;561 }562 promises.push(session.send('Page.setForcedAppearance', {563 appearance564 }));565 let reducedMotionWk = undefined;566 switch (reducedMotion) {567 case 'reduce':568 reducedMotionWk = 'Reduce';569 break;570 case 'no-preference':571 reducedMotionWk = 'NoPreference';572 break;573 }574 promises.push(session.send('Page.setForcedReducedMotion', {575 reducedMotion: reducedMotionWk576 }));577 await Promise.all(promises);578 }579 async updateExtraHTTPHeaders() {580 await this._updateState('Network.setExtraHTTPHeaders', {581 headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false582 /* lowerCase */583 )584 });585 }586 _calculateExtraHTTPHeaders() {587 const locale = this._browserContext._options.locale;588 const headers = network.mergeHeaders([this._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders, locale ? network.singleHeader('Accept-Language', locale) : undefined]);589 return headers;590 }591 async updateEmulateMedia() {592 const colorScheme = this._page._state.colorScheme;593 const reducedMotion = this._page._state.reducedMotion;594 await this._forAllSessions(session => WKPage._setEmulateMedia(session, this._page._state.mediaType, colorScheme, reducedMotion));595 }596 async setEmulatedSize(emulatedSize) {597 (0, _utils.assert)(this._page._state.emulatedSize === emulatedSize);598 await this._updateViewport();599 }600 async bringToFront() {601 this._pageProxySession.send('Target.activate', {602 targetId: this._session.sessionId603 });604 }605 async _updateViewport() {...
ffPage.js
Source:ffPage.js
...317 }318 async bringToFront() {319 await this._session.send('Page.bringToFront', {});320 }321 async updateEmulateMedia() {322 const colorScheme = this._page._state.colorScheme === null ? undefined : this._page._state.colorScheme;323 const reducedMotion = this._page._state.reducedMotion === null ? undefined : this._page._state.reducedMotion;324 const forcedColors = this._page._state.forcedColors === null ? undefined : this._page._state.forcedColors;325 await this._session.send('Page.setEmulatedMedia', {326 // Empty string means reset.327 type: this._page._state.mediaType === null ? '' : this._page._state.mediaType,328 colorScheme,329 reducedMotion,330 forcedColors331 });332 }333 async updateRequestInterception() {334 await this._networkManager.setRequestInterception(this._page._needsRequestInterception());335 }...
page.js
Source:page.js
...247 if (options.media !== undefined) this._state.mediaType = options.media;248 if (options.colorScheme !== undefined) this._state.colorScheme = options.colorScheme;249 if (options.reducedMotion !== undefined) this._state.reducedMotion = options.reducedMotion;250 if (options.forcedColors !== undefined) this._state.forcedColors = options.forcedColors;251 await this._delegate.updateEmulateMedia();252 await this._doSlowMo();253 }254 async setViewportSize(viewportSize) {255 this._state.emulatedSize = {256 viewport: { ...viewportSize257 },258 screen: { ...viewportSize259 }260 };261 await this._delegate.setEmulatedSize(this._state.emulatedSize);262 await this._doSlowMo();263 }264 viewportSize() {265 var _this$_state$emulated;...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 console.log('Page loaded with device size: ', window.innerWidth, 'x', window.innerHeight);8 });9 await context._updateEmulateMedia({10 screenSize: { width: 1920, height: 1080 },11 viewPosition: { x: 0, y: 0 },12 viewSize: { width: 1920, height: 1080 },13 });14 await page.evaluate(() => {15 console.log('Page loaded with device size: ', window.innerWidth, 'x', window.innerHeight);16 });17 await browser.close();18})();19const { webkit } = require('playwright');20(async () => {21 const browser = await webkit.launch();22 const context = await browser.newContext({23 viewport: {24 }25 });26 const page = await context.newPage();27 await page.screenshot({ path: 'google.png' });28 await browser.close();29})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.emulateMedia({ media: 'print' });7 await page.screenshot({ path: 'print.png' });8 await page.emulateMedia({ media: 'screen' });9 await page.screenshot({ path: 'screen.png' });10 await browser.close();11})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.emulateMedia({ media: 'print' });7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.emulateMedia({ media: 'print' });16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.emulateMedia({ media: 'print' });25 await page.screenshot({ path: `example.png` });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.emulateMedia({ media: 'print' });34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.emulateMedia({ media: 'print' });43 await page.screenshot({ path: `example.png` });
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.updateEmulateMedia('screen');7 await page.screenshot({ path: 'screenshot.png' });8 await browser.close();9})();10module.exports = {11 use: {12 },13};
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.evaluate(() => {7 const width = 800;8 const height = 600;9 window.innerWidth = width;10 window.innerHeight = height;11 window.outerWidth = width;12 window.outerHeight = height;13 window.screen = { width, height };14 });15 await page.updateEmulateMedia();16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright.chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.evaluate(() => {25 const width = 800;26 const height = 600;27 window.innerWidth = width;28 window.innerHeight = height;29 window.outerWidth = width;30 window.outerHeight = height;31 window.screen = { width, height };32 });33 await page.updateEmulateMedia();34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const playwright = require('playwright');38(async () => {39 const browser = await playwright.chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.evaluate(() => {43 const width = 800;44 const height = 600;45 window.innerWidth = width;46 window.innerHeight = height;47 window.outerWidth = width;48 window.outerHeight = height;49 window.screen = { width, height };50 });51 await page.updateEmulateMedia();52 await page.screenshot({ path: `example.png` });53 await browser.close();54})();55const playwright = require('playwright');56(async () => {57 const browser = await playwright.chromium.launch();
Using AI Code Generation
1const { chromium } = require('playwright');2const { updateEmulateMedia } = require('playwright/lib/server/browserContext');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await updateEmulateMedia(context, { colorScheme: 'dark' });7 const page = await context.newPage();8 await page.screenshot({ path: 'screenshot.png' });9 await browser.close();10})();11const { chromium } = require('playwright');12const { updateEmulateMedia } = require('playwright/lib/server/browserContext');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 await updateEmulateMedia(context, { colorScheme: 'dark' });17 const page = await context.newPage();18 await page.screenshot({ path: 'screenshot.png' });19 await browser.close();20})();21const { chromium } = require('playwright');22const { updateEmulateMedia } = require('playwright/lib/server/browserContext');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 await updateEmulateMedia(context, { colorScheme: 'dark' });27 const page = await context.newPage();28 await page.screenshot({ path: 'screenshot.png' });
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({ viewport: null });5 const page = await context.newPage();6 await page.waitForTimeout(5000);7 await page.evaluate(() => {8 window.matchMedia = window.matchMedia || function() {9 return {10 addListener : function() {},11 removeListener: function() {}12 };13 };14 });15 await page.evaluate(() => {16 window.updateEmulateMedia = function(emulate) {17 window.matchMedia('(prefers-reduced-motion)').matches = emulate;18 };19 });20 await page.evaluate(() => {window.updateEmulateMedia(true);});21 await page.waitForTimeout(5000);22 await page.evaluate(() => {window.updateEmulateMedia(false);});23 await page.waitForTimeout(5000);24 await browser.close();25})();
Using AI Code Generation
1const { devices } = require('playwright-core/lib/server/deviceDescriptors');2const { chromium } = require('playwright-core');3const iPhone = devices['iPhone 6'];4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext({7 });8 const page = await context.newPage();9 await page.emulateMedia({ media: 'print' });10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();13const devices = {14 'iPhone 6': {15 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.0 Mobile/14G60 Safari/602.1',16 'viewport': {17 },18 },19};20module.exports = { devices };21const { devices } = require('playwright-core/lib/server/deviceDescriptors');22const { chromium } = require('playwright-core');23const iPhone = devices['iPhone 6'];24(async () => {25 const browser = await chromium.launch({ headless: false });26 const context = await browser.newContext({27 });28 const page = await context.newPage();29 await page.updateEmulateMedia({ media: 'print' });30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 });6 const page = await context.newPage();7 await page.evaluate(() => {8 window.playwright = {9 updateEmulateMedia: (mediaType) => {10 document.querySelectorAll('link[media]').forEach((link) => {11 link.media = mediaType;12 });13 }14 };15 });16 await page.evaluate(() => {17 window.playwright.updateEmulateMedia('screen');18 });19 await page.screenshot({ path: `screenshot.png` });20 await browser.close();21})();22{23 "scripts": {24 },25 "dependencies": {26 }27}
Using AI Code Generation
1const playwright = require('playwright');2const { chromium } = playwright;3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext({6 });7 const page = await context.newPage();8 await page.waitForTimeout(2000);9 await page.evaluate(() => {10 window._playwrightInternal.updateEmulateMedia('screen', 'print');11 });12 await page.screenshot({ path: 'screenshot.png' });13 await browser.close();14})();
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!!