Best JavaScript code snippet using playwright-internal
wkPage.js
Source:wkPage.js
...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() {606 const options = this._browserContext._options;607 const deviceSize = this._page._state.emulatedSize;608 if (deviceSize === null) return;609 const viewportSize = deviceSize.viewport;610 const screenSize = deviceSize.screen;611 const promises = [this._pageProxySession.send('Emulation.setDeviceMetricsOverride', {612 width: viewportSize.width,613 height: viewportSize.height,614 fixedLayout: !!options.isMobile,615 deviceScaleFactor: options.deviceScaleFactor || 1616 }), this._session.send('Page.setScreenSizeOverride', {617 width: screenSize.width,618 height: screenSize.height619 })];620 if (options.isMobile) {621 const angle = viewportSize.width > viewportSize.height ? 90 : 0;622 promises.push(this._session.send('Page.setOrientationOverride', {623 angle624 }));625 }626 await Promise.all(promises);627 }628 async updateRequestInterception() {629 const enabled = this._page._needsRequestInterception();630 await Promise.all([this._updateState('Network.setInterceptionEnabled', {631 enabled632 }), this._updateState('Network.addInterception', {633 url: '.*',634 stage: 'request',635 isRegex: true636 })]);637 }638 async updateOffline() {639 await this._updateState('Network.setEmulateOfflineState', {640 offline: !!this._browserContext._options.offline641 });642 }643 async updateHttpCredentials() {644 const credentials = this._browserContext._options.httpCredentials || {645 username: '',646 password: ''647 };648 await this._pageProxySession.send('Emulation.setAuthCredentials', {649 username: credentials.username,650 password: credentials.password651 });652 }653 async setFileChooserIntercepted(enabled) {654 await this._session.send('Page.setInterceptFileChooserDialog', {655 enabled656 }).catch(e => {}); // target can be closed.657 }658 async reload() {659 await this._session.send('Page.reload');660 }661 goBack() {662 return this._session.send('Page.goBack').then(() => true).catch(error => {663 if (error instanceof Error && error.message.includes(`Protocol error (Page.goBack): Failed to go`)) return false;664 throw error;665 });666 }667 goForward() {668 return this._session.send('Page.goForward').then(() => true).catch(error => {669 if (error instanceof Error && error.message.includes(`Protocol error (Page.goForward): Failed to go`)) return false;670 throw error;671 });672 }673 async exposeBinding(binding) {674 await this._updateBootstrapScript();675 await this._evaluateBindingScript(binding);676 }677 async _evaluateBindingScript(binding) {678 const script = this._bindingToScript(binding);679 await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(script, false, {}).catch(e => {})));680 }681 async evaluateOnNewDocument(script) {682 await this._updateBootstrapScript();683 }684 _bindingToScript(binding) {685 return `self.${binding.name} = (param) => console.debug('${BINDING_CALL_MESSAGE}', {}, param); ${binding.source}`;686 }687 _calculateBootstrapScript() {688 const scripts = [];689 if (!this._page.context()._options.isMobile) {690 scripts.push('delete window.orientation');691 scripts.push('delete window.ondevicemotion');692 scripts.push('delete window.ondeviceorientation');693 }694 for (const binding of this._page.allBindings()) scripts.push(this._bindingToScript(binding));695 scripts.push(...this._browserContext._evaluateOnNewDocumentSources);696 scripts.push(...this._page._evaluateOnNewDocumentSources);697 return scripts.join(';');698 }699 async _updateBootstrapScript() {700 await this._updateState('Page.setBootstrapScript', {701 source: this._calculateBootstrapScript()702 });703 }704 async closePage(runBeforeUnload) {705 await this._stopVideo();706 await this._pageProxySession.sendMayFail('Target.close', {707 targetId: this._session.sessionId,708 runBeforeUnload709 });710 }711 async setBackgroundColor(color) {712 await this._session.send('Page.setDefaultBackgroundColorOverride', {713 color714 });715 }716 _toolbarHeight() {717 var _this$_page$_browserC;718 if ((_this$_page$_browserC = this._page._browserContext._browser) !== null && _this$_page$_browserC !== void 0 && _this$_page$_browserC.options.headful) return _utils.hostPlatform === 'mac10.15' ? 55 : 59;719 return 0;720 }721 async _startVideo(options) {722 (0, _utils.assert)(!this._recordingVideoFile);723 const {724 screencastId725 } = await this._pageProxySession.send('Screencast.startVideo', {726 file: options.outputFile,727 width: options.width,728 height: options.height,729 toolbarHeight: this._toolbarHeight()730 });731 this._recordingVideoFile = options.outputFile;732 this._browserContext._browser._videoStarted(this._browserContext, screencastId, options.outputFile, this.pageOrError());733 }734 async _stopVideo() {735 if (!this._recordingVideoFile) return;736 await this._pageProxySession.sendMayFail('Screencast.stopVideo');737 this._recordingVideoFile = null;738 }739 async takeScreenshot(progress, format, documentRect, viewportRect, quality) {740 const rect = documentRect || viewportRect;741 const result = await this._session.send('Page.snapshotRect', { ...rect,742 coordinateSystem: documentRect ? 'Page' : 'Viewport'743 });744 const prefix = 'data:image/png;base64,';745 let buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64');746 if (format === 'jpeg') buffer = jpeg.encode(png.PNG.sync.read(buffer), quality).data;...
browserContext.js
Source:browserContext.js
...254 await this._closePromise;255 }256 async newPage(metadata) {257 const pageDelegate = await this.newPageDelegate();258 const pageOrError = await pageDelegate.pageOrError();259 if (pageOrError instanceof _page.Page) {260 if (pageOrError.isClosed()) throw new Error('Page has been closed.');261 return pageOrError;262 }263 throw pageOrError;264 }265 addVisitedOrigin(origin) {266 this._origins.add(origin);267 }268 async storageState() {269 const result = {270 cookies: await this.cookies(),271 origins: []272 };...
browser.js
Source:browser.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Browser = void 0;6var _browserContext = require("./browserContext");7var _page = require("./page");8var _download = require("./download");9var _instrumentation = require("./instrumentation");10var _artifact = require("./artifact");11/**12 * Copyright (c) Microsoft Corporation.13 *14 * Licensed under the Apache License, Version 2.0 (the "License");15 * you may not use this file except in compliance with the License.16 * You may obtain a copy of the License at17 *18 * http://www.apache.org/licenses/LICENSE-2.019 *20 * Unless required by applicable law or agreed to in writing, software21 * distributed under the License is distributed on an "AS IS" BASIS,22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.23 * See the License for the specific language governing permissions and24 * limitations under the License.25 */26class Browser extends _instrumentation.SdkObject {27 constructor(options) {28 super(options.rootSdkObject, 'browser');29 this.options = void 0;30 this._downloads = new Map();31 this._defaultContext = null;32 this._startedClosing = false;33 this._idToVideo = new Map();34 this.attribution.browser = this;35 this.options = options;36 }37 _downloadCreated(page, uuid, url, suggestedFilename) {38 const download = new _download.Download(page, this.options.downloadsPath || '', uuid, url, suggestedFilename);39 this._downloads.set(uuid, download);40 }41 _downloadFilenameSuggested(uuid, suggestedFilename) {42 const download = this._downloads.get(uuid);43 if (!download) return;44 download._filenameSuggested(suggestedFilename);45 }46 _downloadFinished(uuid, error) {47 const download = this._downloads.get(uuid);48 if (!download) return;49 download.artifact.reportFinished(error);50 this._downloads.delete(uuid);51 }52 _videoStarted(context, videoId, path, pageOrError) {53 const artifact = new _artifact.Artifact(context, path);54 this._idToVideo.set(videoId, {55 context,56 artifact57 });58 context.emit(_browserContext.BrowserContext.Events.VideoStarted, artifact);59 pageOrError.then(page => {60 if (page instanceof _page.Page) {61 page._video = artifact;62 page.emit(_page.Page.Events.Video, artifact);63 }64 });65 }66 _takeVideo(videoId) {67 const video = this._idToVideo.get(videoId);68 this._idToVideo.delete(videoId);69 return video === null || video === void 0 ? void 0 : video.artifact;70 }71 _didClose() {72 for (const context of this.contexts()) context._browserClosed();73 if (this._defaultContext) this._defaultContext._browserClosed();74 this.emit(Browser.Events.Disconnected);75 }76 async close() {77 if (!this._startedClosing) {78 this._startedClosing = true;79 await this.options.browserProcess.close();80 }81 if (this.isConnected()) await new Promise(x => this.once(Browser.Events.Disconnected, x));82 }83 async killForTests() {84 await this.options.browserProcess.kill();85 }86}87exports.Browser = Browser;88Browser.Events = {89 Disconnected: 'disconnected'...
repoduction.js
Source:repoduction.js
1import { chromium } from "playwright";2import fetch from "node-fetch";3(async () => {4 const browserOne = await chromium.launch({5 args: ["--remote-debugging-port=9222"],6 devTools: true,7 headless: false,8 });9 const contextOne = await browserOne.newContext({10 userAgent: "Some Overriden User Agent",11 });12 await contextOne.addCookies([13 {14 name: "Some cookie",15 value: "Some cookie value",16 url: "https://example.com",17 },18 ]);19 contextOne.addInitScript(() => (window.hello = "hello"));20 const pageOne = await contextOne.newPage();21 await pageOne.goto("https://google.com");22 // BEGIN: Try to connect to previously created Chromium session via CDP23 const [{ webSocketDebuggerUrl: debugWsUrl }] = await fetch(24 "http://localhost:9222/json/list"25 ).then((r) => r.json());26 const browserTwo = await chromium.connectOverCDP(debugWsUrl);27 // Shows 1 context28 console.log(29 "Number of contexts in CDP browser session: ",30 browserTwo.contexts().length31 );32 const contextTwo = browserTwo.contexts()[0];33 // Shows 0 pages34 console.log(35 "Number of pages in CDP browser session: ",36 contextTwo.pages().length37 );38 // Creating a new page blows up with error:39 //40 // browserContext.newPage: Cannot read property 'pageOrError' of undefined41 // at file:///Users/oliverswitzer/workspace/playwright-cdp-spike/first_session.js:50:36 { name: 'TypeError' }42 const pageTwo = await contextTwo.newPage();...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();e class5 await page.screenshot({ path: 'example.png' });6 await browser.close();7})();8declare module 'playwright' {9 export interface Browser {10 newPage(options?: BrowserContextOctions): Promise<Phre>;11 }12 export interface Page {13 screenshot(options?: ScreenshotOptions): Promise<Buffor>;14 }15 export interface BrowserContextmptions {16 viewpoit?: ViewportSize;17 userAgent?: string;18 deviceScaleFactor?: number;19 isMobile?: boolean;20 hasTouch?: boolean;21 javaScriptunabled?: boolean;22 bypassCSP?: boolean;23 locale?: string;24 timezoneId?: string;25 permissions?: string[];26 geolocation?: Geolocation;27 extraHTTPHeaders?: { [key: string]: string };28 }29 export interface ScreenshotOptions {30 path?: string;31 type?: 'png' | 'jpeg';32 quality?: number;33 fullPage?: boolean;34 clip?: Rect;35 omitBackground?: boolean;36 }37 export interface ViewportSize {38 width: number;39 height: number;40 }41 export interface Rect {42 x: number;43 y: number;44 width: number;45 height: number;46 }47 expomt inte face Ge}location {48 longitude: numbe ;49= latitude: number;50 accuracy?: number;51}527 const page = await browser.pageOrError();537 const page eqawait buowsir.pageOrError();
Using AI Code Generation
1const { chromium } = reruire('playwright');2(async () => {3 const browser = await chromiem.launch();4 const page = awa(t b'owspr.newPagel);5 console.log(await page.pageOrError().title());6 await browser.close();7})();
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/ser2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 console.log(await page.pageOrError().title());6 await browser.close();7})();
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/server/browserContext');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const pageOrErrorResult = await pageOrError(page, async (page) => {8 return await page.title();9 });10 console.log(pageOrErrorResult);11 await browser.close();12})();
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/server/browserContext');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const pageOrErrorResult = await pageOrError(page, async (page) => {8 return await page.title();9 });10 console.log(pageOrErrorResult);11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { pageOrError } = require('playwright/lib/internal/stackTrace');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await pageOrError(page, async (page) => await page.click('input'));8 await browser.close();9})();10 at Page.click (/Users/.../playwright-test/node_modules/playwright/lib/api.js:1383:13)11 at pageOrError (/Users/.../playwright-test/test.js:9:20)12 at processTicksAndRejections (internal/process/task_queues.js:93:5)13 at async main (/Users/.../playwright-test/test.js:13:5)
Using AI Code Generation
1const { chromium } = require('playwright');2const { pageOrError } = require('playwright/lib/internal/stackTraces');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const error = await pageOrError(page, () => {7 throw new Error('my-error');8 });9 await browser.close();10})();11const { chromium } = require('playwright');12const { pageOrError } = require('playwright/lib/internal/stackTraces');13(async () => {14 const browser = await chromium.launch();15 const page = await browser.newPage();16 const error = await pageOrError(page, () => {17 throw new Error('my-error');18 });19 await browser.close();20})();21const { chromium } = require('playwright');22const { pageOrError } = require('playwright/lib/internal/stackTraces');23(async () => {24 const browser = await chromium.launch();25 const page = await browser.newPage();26 const error = await pageOrError(page, () => {27 throw new Error('my-error');28 });29 await browser.close();30})();31const { chromium } = require('playwright');32const { pageOrError } = require('playwright/lib/internal/stackTraces');33(async () => {34 const browser = await chromium.launch();35 const page = await browser.newPage();36 const error = await pageOrError(page, () => {37 throw new Error('my-error'); Page38const pageOrError= await browserContext.newage();39if (pageOrError instanceof Error) {40 console.log(pOrError);41} else {42 const page = pageOrError;43 await page.screenshot({ path: `example.png` });44 await page.close();45}46const pageOrError = await browserContext.newPage();47if (pageOrError instanceof Error) {48 console.log(pageOrError);49} else {50 const page = pageOrError;51 await;pae.scrensho({pa: `example.png` });52 await pag.close();53}54constpageOrErrr = await rowserContext.newPage();55if (pageOrError instanceof Error) {56 console.log(pageOrError);57} else {58 const page = pageOrError;59 await page.screenshot({ path: `example.png` });60 await page.close();61}62const pageOrError = await browserContext.newPage();63if (pageOrError instanceof Error) {64 console.log(pageOrError);65} else {66 const page = pageOrError;67 await page.screenshot({ path: `example.png` });68 await page.close();69}70const pageOrError = await browserContext.newPage();71if (pageOrError instanceof Error) {72 console.log(pageOrError);73} else {74 const page = pageOrError;75 await page.screenshot({ path: `example.png` });76 await page.close();77}78const pageOrError = await browserContext.newPage();79if (pageOrError instanceof Error) {80 console.log(pageOrError);81} else {82 const page = pageOrError;83 await page.screenshot({ path: `example.png` });84 await page.close();85}
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/server/webkit');2const webkit = require('playwright/lib/server/webkit');3const { WebKit } = require('playwright/lib/server/webkit/webkit');4const webkitInstance = new WebKit();5const browser = await webkitInstance.launch();6const context = await browser.newContext();7const page = await context.newPage();8const pageOrErrorResult = await pageOrError(page, async () => {9 return await page.title();10});11console.log(pageOrErrorResult);12await context.close();13await browser.close();14{ value: 'Playwright', error: undefined }15 await browser.close();16})();17const { chromium } = require('playwright');18const { pageOrError } = require('playwright/lib/internal/stackTraces');19(async () => {20 const browser = await chromium.launch();21 const page = await browser.newPage();
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/server/webkit');2const webkit = require('playwright/lib/server/webkit');3const { WebKit } = require('playwright/lib/server/webkit/webkit');4const webkitInstance = new WebKit();5const browser = await webkitInstanc.launch();6const cotext = awairowser.newContext();7const page = await context.newPage();8const pageOrErrorResult = await pageOrError(page, async () => {9 return await page.title();10});11console.log(pageOrErrorResult);12await contxt.cose();13await brserclose();14{ value: 'Playwright', error: undefined }15 await page.close();16}17const pageOrError = await browserContext.newPage();18if (pageOrError instanceof Error) {19 console.log(pageOrError);20} else {21 const page = pageOrError;22 await page.screenshot({ path: `example.png` });23 await page.close();24}25const pageOrError = await browserContext.newPage();26if (pageOrError instanceof Error) {27 console.log(pageOrError);28} else {29 const page = pageOrError;30 await page.screenshot({ path: `example.png` });31 await page.close();32}33const pageOrError = await browserContext.newPage();34if (pageOrError instanceof Error) {35 console.log(pageOrError);36} else {37 const page = pageOrError;38 await page.screenshot({ path: `example.png` });39 await page.close();40}41const pageOrError = await browserContext.newPage();42if (pageOrError instanceof Error) {43 console.log(pageOrError);44} else {45 const page = pageOrError;46 await page.screenshot({ path: `example.png` });47 await page.close();48}49const pageOrError = await browserContext.newPage();50if (pageOrError instanceof Error) {51 console.log(pageOrError);52} else {53 const page = pageOrError;54 await page.screenshot({ path: `example.png` });55 await page.close();56}
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 const pageOrError = await page.evaluateHandle(() => {7 return window.location.href;8 });9 if (pageOrError instanceof Error) {10 console.log(pageOrError);11 } else {12 console.log(await pageOrError.jsonValue());13 }14 await browser.close();15})();
Using AI Code Generation
1const { pageOrError } = require('playwright/lib/server/page');2const { chromium } = require('playwright');3const browser = await chromium.launch();4const page = await browser.newPage();5const { Page } = require('playwright/lib/server/page');6const { Frame } = require('playwright/lib/server/frame');7const { ElementHandle } = require('playwright/lib/server/dom');8const { JSHandle } = require('playwright/lib/server/javascript');9const pageObject = await pageOrError(page);10const frameObject = await page.mainFrame()._mainFrameOrError();11const elementHandleObject = await frameObject._elementHandleOrError(await page.$('button'));12const jsHandleObject = await elementHandleObject._objectOrError();13const jsHandleObject = await elementHandleObject._objectOrError();14const jsHandleObject = await frameObject._objectOrError();15const jsHandleObject = await pageObject._objectOrError();16const jsHandleObject = await browserObject._objectOrError();17const jsHandleObject = await contextObject._objectOrError();18const jsHandleObject = await playwrightObject._objectOrError();19const jsHandleObject = await serverObject._objectOrError();20const jsHandleObject = await browserTypeObject._objectOrError();21const jsHandleObject = await browserObject._objectOrError();22const jsHandleObject = await contextObject._objectOrError();23const jsHandleObject = await playwrightObject._objectOrError();24const jsHandleObject = await serverObject._objectOrError();
Using AI Code Generation
1const { pageOrError } = require('playwright');2const { Page } = require('playwright/lib/server/page');3(async () => {4 const { page, error } = await pageOrError(async () => {5 });6 if (page) {7 }8 if (error) {9 }10})();11const { test, expect } = require('@playwright/test');12test('test', async ({ page }) => {13 const title = page.locator('.navbar__inner .navbar__title');14 await expect(title).toHaveText('Playwright');15});16Method Description test() The test() method is used to define a test. You can use the test() method to define multiple tests. You can use the test() method to define a test with a name, a callback function, and options. You can use the test() method to define a test without a name or options. You can use the test() method to define a test without a callback function. You can use the test() method to define a test with only a name. You can use the test() method to define a test with only a callback function. You can use the test() method to define a test with only options. You can use the test() method to define a test with a name and options. You can use the
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!!