Best JavaScript code snippet using playwright-internal
wkPage.js
Source:wkPage.js
...107 if (contextOptions.javaScriptEnabled === false) promises.push(this._pageProxySession.send('Emulation.setJavaScriptEnabled', {108 enabled: false109 }));110 promises.push(this._updateViewport());111 promises.push(this.updateHttpCredentials());112 if (this._browserContext._permissions.size) {113 for (const [key, value] of this._browserContext._permissions) promises.push(this._grantPermissions(key, value));114 }115 if (this._browserContext._options.recordVideo) {116 const outputFile = _path.default.join(this._browserContext._options.recordVideo.dir, (0, _utils.createGuid)() + '.webm');117 promises.push(this._browserContext._ensureVideosPath().then(() => {118 return this._startVideo({ // validateBrowserContextOptions ensures correct video size.119 ...this._browserContext._options.recordVideo.size,120 outputFile121 });122 }));123 }124 await Promise.all(promises);125 }126 _setSession(session) {127 _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);128 this._session = session;129 this.rawKeyboard.setSession(session);130 this.rawMouse.setSession(session);131 this._addSessionListeners();132 this._workers.setSession(session);133 } // This method is called for provisional targets as well. The session passed as the parameter134 // may be different from the current session and may be destroyed without becoming current.135 async _initializeSession(session, provisional, resourceTreeHandler) {136 await this._initializeSessionMayThrow(session, resourceTreeHandler).catch(e => {137 // Provisional session can be disposed at any time, for example due to new navigation initiating138 // a new provisional page.139 if (provisional && session.isDisposed()) return; // Swallow initialization errors due to newer target swap in,140 // since we will reinitialize again.141 if (this._session === session) throw e;142 });143 }144 async _initializeSessionMayThrow(session, resourceTreeHandler) {145 const [, frameTree] = await Promise.all([// Page agent must be enabled before Runtime.146 session.send('Page.enable'), session.send('Page.getResourceTree')]);147 resourceTreeHandler(frameTree);148 const promises = [// Resource tree should be received before first execution context.149 session.send('Runtime.enable'), session.send('Page.createUserWorld', {150 name: UTILITY_WORLD_NAME151 }).catch(_ => {}), // Worlds are per-process152 session.send('Console.enable'), session.send('Network.enable'), this._workers.initializeSession(session)];153 if (this._page._needsRequestInterception()) {154 promises.push(session.send('Network.setInterceptionEnabled', {155 enabled: true156 }));157 promises.push(session.send('Network.addInterception', {158 url: '.*',159 stage: 'request',160 isRegex: true161 }));162 }163 const contextOptions = this._browserContext._options;164 if (contextOptions.userAgent) promises.push(session.send('Page.overrideUserAgent', {165 value: contextOptions.userAgent166 }));167 if (this._page._state.mediaType || this._page._state.colorScheme || this._page._state.reducedMotion) promises.push(WKPage._setEmulateMedia(session, this._page._state.mediaType, this._page._state.colorScheme, this._page._state.reducedMotion));168 const bootstrapScript = this._calculateBootstrapScript();169 if (bootstrapScript.length) promises.push(session.send('Page.setBootstrapScript', {170 source: bootstrapScript171 }));172 this._page.frames().map(frame => frame.evaluateExpression(bootstrapScript, false, undefined).catch(e => {}));173 if (contextOptions.bypassCSP) promises.push(session.send('Page.setBypassCSP', {174 enabled: true175 }));176 if (this._page._state.emulatedSize) {177 promises.push(session.send('Page.setScreenSizeOverride', {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() {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 }...
crBrowser.js
Source:crBrowser.js
...381 for (const page of this.pages()) await page._delegate.updateOffline();382 }383 async _doSetHTTPCredentials(httpCredentials) {384 this._options.httpCredentials = httpCredentials;385 for (const page of this.pages()) await page._delegate.updateHttpCredentials();386 }387 async _doAddInitScript(source) {388 this._evaluateOnNewDocumentSources.push(source);389 for (const page of this.pages()) await page._delegate.evaluateOnNewDocument(source);390 }391 async _doExposeBinding(binding) {392 for (const page of this.pages()) await page._delegate.exposeBinding(binding);393 }394 async _doUpdateRequestInterception() {395 for (const page of this.pages()) await page._delegate.updateRequestInterception();396 }397 async _doClose() {398 (0, _utils.assert)(this._browserContextId);399 await this._browser._session.send('Target.disposeBrowserContext', {...
wkBrowser.js
Source:wkBrowser.js
...263 for (const page of this.pages()) await page._delegate.updateOffline();264 }265 async _doSetHTTPCredentials(httpCredentials) {266 this._options.httpCredentials = httpCredentials;267 for (const page of this.pages()) await page._delegate.updateHttpCredentials();268 }269 async _doAddInitScript(source) {270 this._evaluateOnNewDocumentSources.push(source);271 for (const page of this.pages()) await page._delegate._updateBootstrapScript();272 }273 async _doExposeBinding(binding) {274 for (const page of this.pages()) await page._delegate.exposeBinding(binding);275 }276 async _doUpdateRequestInterception() {277 for (const page of this.pages()) await page._delegate.updateRequestInterception();278 }279 _onClosePersistent() {}280 async _doClose() {281 (0, _utils.assert)(this._browserContextId);...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.updateHttpCredentials({ username: 'user', password: 'password' });6 const page = await context.newPage();7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 await context.updateHttpCredentials({ username: 'user', password: 'password' });14 const page = await context.newPage();15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 await context.updateHttpCredentials({ username: 'user', password: 'password' });22 const page = await context.newPage();23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 await context.updateHttpCredentials({ username: 'user', password: 'password' });30 const page = await context.newPage();31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 await context.updateHttpCredentials({ username: 'user', password: 'password' });38 const page = await context.newPage();39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {
Using AI Code Generation
1const { chromium } = require('playwright');2const { updateHttpCredentials } = require('playwright/lib/server/browserContext');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 updateHttpCredentials(context, 'username', 'password');8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { updateHttpCredentials } = require('playwright/lib/server/browserType');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await updateHttpCredentials(context, 'username', 'password');7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();11 at Object.dispatch (C:\Users\user\Documents\GitHub\playwright\test\lib\frameManager.js:109:15)12 at FrameManager._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\frameManager.js:44:37)13 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)14 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)15 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)16 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)17 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)18 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)19 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25:29)20 at CDPSession._onMessage (C:\Users\user\Documents\GitHub\playwright\test\lib\cdp.js:25: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 browser.close();7})();8await context._browserContext.updateHttpCredentials({ username: 'user', password: 'pass' });9at CDPSession.send (/home/user/node_modules/playwright/lib/server/cjs/protocol/protocol.js:92:19)10at Network.enable (/home/user/node_modules/playwright/lib/server/cjs/protocol/protocol.js:130:17)11at NetworkManager.initialize (/home/user/node_modules/playwright/lib/server/cjs/chromium/crNetworkManager.js:54:17)12at async BrowserContext._initialize (/home/user/node_modules/playwright/lib/server/cjs/browserContext.js:122:9)13at async BrowserContext._doSlowMo (/home/user/node_modules/playwright/lib/server/cjs/browserContext.js:103:5)14at async BrowserContext.newPage (/home/user/node_modules/playwright/lib/server/cjs/browserContext.js:80:5)15at async Object.<anonymous> (/home/user/playwright_test.js:11:21)16at async ModuleJob.run (internal/modules/esm/module_job.js:152:23)17at async async Promise.all (index 0)18at async ESMLoader.import (/home/user/node_modules/playwright/lib/server/cjs/esm/loader.js:145:24)
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!!