Best JavaScript code snippet using playwright-internal
wkPage.js
Source:wkPage.js
...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;...
crPage.js
Source:crPage.js
...344 _isMainFrame() {345 return this._targetId === this._crPage._targetId;346 }347 _addRendererListeners() {348 this._eventListeners.push(...[_eventsHelper.eventsHelper.addEventListener(this._client, 'Log.entryAdded', event => this._onLogEntryAdded(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameDetached', event => this._onFrameDetached(event.frameId, event.reason)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameRequestedNavigation', event => this._onFrameRequestedNavigation(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.javascriptDialogOpening', event => this._onDialog(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.bindingCalled', event => this._onBindingCalled(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.consoleAPICalled', event => this._onConsoleAPI(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()), _eventsHelper.eventsHelper.addEventListener(this._client, 'Target.attachedToTarget', event => this._onAttachedToTarget(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Target.detachedFromTarget', event => this._onDetachedFromTarget(event))]);349 }350 _addBrowserListeners() {351 this._eventListeners.push(...[_eventsHelper.eventsHelper.addEventListener(this._client, 'Inspector.targetCrashed', event => this._onTargetCrashed()), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.screencastFrame', event => this._onScreencastFrame(event)), _eventsHelper.eventsHelper.addEventListener(this._client, 'Page.windowOpen', event => this._onWindowOpen(event))]);352 }353 async _initialize(hasUIWindow) {354 if (hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {355 const {356 windowId357 } = await this._client.send('Browser.getWindowForTarget');358 this._windowId = windowId;359 }360 let screencastOptions;361 if (this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) {362 const screencastId = (0, _utils.createGuid)();363 const outputFile = _path.default.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + '.webm');364 screencastOptions = { // validateBrowserContextOptions ensures correct video size.365 ...this._crPage._browserContext._options.recordVideo.size,366 outputFile367 };368 await this._crPage._browserContext._ensureVideosPath(); // Note: it is important to start video recorder before sending Page.startScreencast,369 // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.370 await this._createVideoRecorder(screencastId, screencastOptions);371 this._crPage.pageOrError().then(p => {372 if (p instanceof Error) this._stopVideoRecording().catch(() => {});373 });374 }375 let lifecycleEventsEnabled;376 if (!this._isMainFrame()) this._addRendererListeners();377 this._addBrowserListeners();378 const promises = [this._client.send('Page.enable'), this._client.send('Page.getFrameTree').then(({379 frameTree380 }) => {381 if (this._isMainFrame()) {382 this._handleFrameTree(frameTree);383 this._addRendererListeners();384 }385 const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)];386 for (const frame of localFrames) {387 // Note: frames might be removed before we send these.388 this._client._sendMayFail('Page.createIsolatedWorld', {389 frameId: frame._id,390 grantUniveralAccess: true,391 worldName: UTILITY_WORLD_NAME392 });393 for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source, false, undefined).catch(e => {});394 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});395 }396 const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';397 if (isInitialEmptyPage) {398 // Ignore lifecycle events for the initial empty page. It is never the final page399 // hence we are going to get more lifecycle updates after the actual navigation has400 // started (even if the target url is about:blank).401 lifecycleEventsEnabled.catch(e => {}).then(() => {402 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));403 });404 } else {405 this._firstNonInitialNavigationCommittedFulfill();406 this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));407 }408 }), this._client.send('Log.enable', {}), lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', {409 enabled: true410 }), this._client.send('Runtime.enable', {}), this._client.send('Page.addScriptToEvaluateOnNewDocument', {411 source: '',412 worldName: UTILITY_WORLD_NAME413 }), this._networkManager.initialize(), this._client.send('Target.setAutoAttach', {414 autoAttach: true,415 waitForDebuggerOnStart: true,416 flatten: true417 })];418 if (this._isMainFrame()) promises.push(this._client.send('Emulation.setFocusEmulationEnabled', {419 enabled: true420 }));421 const options = this._crPage._browserContext._options;422 if (options.bypassCSP) promises.push(this._client.send('Page.setBypassCSP', {423 enabled: true424 }));425 if (options.ignoreHTTPSErrors) promises.push(this._client.send('Security.setIgnoreCertificateErrors', {426 ignore: true427 }));428 if (this._isMainFrame()) promises.push(this._updateViewport());429 if (options.hasTouch) promises.push(this._client.send('Emulation.setTouchEmulationEnabled', {430 enabled: true431 }));432 if (options.javaScriptEnabled === false) promises.push(this._client.send('Emulation.setScriptExecutionDisabled', {433 value: true434 }));435 if (options.userAgent || options.locale) promises.push(this._client.send('Emulation.setUserAgentOverride', {436 userAgent: options.userAgent || '',437 acceptLanguage: options.locale438 }));439 if (options.locale) promises.push(emulateLocale(this._client, options.locale));440 if (options.timezoneId) promises.push(emulateTimezone(this._client, options.timezoneId));441 promises.push(this._updateGeolocation(true));442 promises.push(this._updateExtraHTTPHeaders(true));443 promises.push(this._updateRequestInterception());444 promises.push(this._updateOffline(true));445 promises.push(this._updateHttpCredentials(true));446 promises.push(this._updateEmulateMedia(true));447 for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));448 for (const source of this._crPage._browserContext._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));449 for (const source of this._crPage._page._evaluateOnNewDocumentSources) promises.push(this._evaluateOnNewDocument(source, 'main'));450 if (screencastOptions) promises.push(this._startVideoRecording(screencastOptions));451 promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));452 promises.push(this._firstNonInitialNavigationCommittedPromise);453 await Promise.all(promises);454 }455 dispose() {456 _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);457 this._networkManager.dispose();458 this._crPage._sessions.delete(this._targetId);459 }460 async _navigate(frame, url, referrer) {461 const response = await this._client.send('Page.navigate', {462 url,463 referrer,464 frameId: frame._id465 });466 if (response.errorText) throw new Error(`${response.errorText} at ${url}`);467 return {468 newDocumentId: response.loaderId469 };470 }471 _onLifecycleEvent(event) {472 if (this._eventBelongsToStaleFrame(event.frameId)) return;473 if (event.name === 'load') this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');else if (event.name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');474 }475 _onFrameStoppedLoading(frameId) {476 if (this._eventBelongsToStaleFrame(frameId)) return;477 this._page._frameManager.frameStoppedLoading(frameId);478 }479 _handleFrameTree(frameTree) {480 this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);481 this._onFrameNavigated(frameTree.frame, true);482 if (!frameTree.childFrames) return;483 for (const child of frameTree.childFrames) this._handleFrameTree(child);484 }485 _eventBelongsToStaleFrame(frameId) {486 const frame = this._page._frameManager.frame(frameId); // Subtree may be already gone because some ancestor navigation destroyed the oopif.487 if (!frame) return true; // When frame goes remote, parent process may still send some events488 // related to the local frame before it sends frameDetached.489 // In this case, we already have a new session for this frame, so events490 // in the old session should be ignored.491 const session = this._crPage._sessionForFrame(frame);492 return session && session !== this && !session._swappedIn;493 }494 _onFrameAttached(frameId, parentFrameId) {495 const frameSession = this._crPage._sessions.get(frameId);496 if (frameSession && frameId !== this._targetId) {497 // This is a remote -> local frame transition.498 frameSession._swappedIn = true;499 const frame = this._page._frameManager.frame(frameId); // Frame or even a whole subtree may be already gone, because some ancestor did navigate.500 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);501 return;502 }503 if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {504 // Parent frame may be gone already because some ancestor frame navigated and505 // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.506 // Be careful to not confuse this with "main frame navigated cross-process" scenario507 // where parentFrameId is null.508 return;509 }510 this._page._frameManager.frameAttached(frameId, parentFrameId);511 }512 _onFrameNavigated(framePayload, initial) {513 if (this._eventBelongsToStaleFrame(framePayload.id)) return;514 this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);515 if (!initial) this._firstNonInitialNavigationCommittedFulfill();516 }517 _onFrameRequestedNavigation(payload) {518 if (this._eventBelongsToStaleFrame(payload.frameId)) return;519 if (payload.disposition === 'currentTab') this._page._frameManager.frameRequestedNavigation(payload.frameId);520 }521 _onFrameNavigatedWithinDocument(frameId, url) {522 if (this._eventBelongsToStaleFrame(frameId)) return;523 this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);524 }525 _onFrameDetached(frameId, reason) {526 if (this._crPage._sessions.has(frameId)) {527 // This is a local -> remote frame transtion, where528 // Page.frameDetached arrives after Target.attachedToTarget.529 // We've already handled the new target and frame reattach - nothing to do here.530 return;531 }532 if (reason === 'swap') {533 // This is a local -> remote frame transtion, where534 // Page.frameDetached arrives before Target.attachedToTarget.535 // We should keep the frame in the tree, and it will be used for the new target.536 const frame = this._page._frameManager.frame(frameId);537 if (frame) this._page._frameManager.removeChildFramesRecursively(frame);538 return;539 } // Just a regular frame detach.540 this._page._frameManager.frameDetached(frameId);541 }542 _onExecutionContextCreated(contextPayload) {543 const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;544 if (!frame || this._eventBelongsToStaleFrame(frame._id)) return;545 const delegate = new _crExecutionContext.CRExecutionContext(this._client, contextPayload);546 let worldName = null;547 if (contextPayload.auxData && !!contextPayload.auxData.isDefault) worldName = 'main';else if (contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';548 const context = new dom.FrameExecutionContext(delegate, frame, worldName);549 context[contextDelegateSymbol] = delegate;550 if (worldName) frame._contextCreated(worldName, context);551 this._contextIdToContext.set(contextPayload.id, context);552 }553 _onExecutionContextDestroyed(executionContextId) {554 const context = this._contextIdToContext.get(executionContextId);555 if (!context) return;556 this._contextIdToContext.delete(executionContextId);557 context.frame._contextDestroyed(context);558 }559 _onExecutionContextsCleared() {560 for (const contextId of Array.from(this._contextIdToContext.keys())) this._onExecutionContextDestroyed(contextId);561 }562 _onAttachedToTarget(event) {563 const session = _crConnection.CRConnection.fromSession(this._client).session(event.sessionId);564 if (event.targetInfo.type === 'iframe') {565 // Frame id equals target id.566 const targetId = event.targetInfo.targetId;567 const frame = this._page._frameManager.frame(targetId);568 if (!frame) return; // Subtree may be already gone due to renderer/browser race.569 this._page._frameManager.removeChildFramesRecursively(frame);570 const frameSession = new FrameSession(this._crPage, session, targetId, this);571 this._crPage._sessions.set(targetId, frameSession);572 frameSession._initialize(false).catch(e => e);573 return;574 }575 if (event.targetInfo.type !== 'worker') {576 // Ideally, detaching should resume any target, but there is a bug in the backend.577 session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {578 this._client._sendMayFail('Target.detachFromTarget', {579 sessionId: event.sessionId580 });581 });582 return;583 }584 const url = event.targetInfo.url;585 const worker = new _page.Worker(this._page, url);586 this._page._addWorker(event.sessionId, worker);587 session.once('Runtime.executionContextCreated', async event => {588 worker._createExecutionContext(new _crExecutionContext.CRExecutionContext(session, event.context));589 }); // This might fail if the target is closed before we initialize.590 session._sendMayFail('Runtime.enable');591 session._sendMayFail('Network.enable');592 session._sendMayFail('Runtime.runIfWaitingForDebugger');593 session.on('Runtime.consoleAPICalled', event => {594 const args = event.args.map(o => worker._existingExecutionContext.createHandle(o));595 this._page._addConsoleMessage(event.type, args, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));596 });597 session.on('Runtime.exceptionThrown', exception => this._page.emit(_page.Page.Events.PageError, (0, _crProtocolHelper.exceptionToError)(exception.exceptionDetails))); // TODO: attribute workers to the right frame.598 this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId));599 }600 _onDetachedFromTarget(event) {601 // This might be a worker...602 this._page._removeWorker(event.sessionId); // ... or an oopif.603 const childFrameSession = this._crPage._sessions.get(event.targetId);604 if (!childFrameSession) return; // Usually, we get frameAttached in this session first and mark child as swappedIn.605 if (childFrameSession._swappedIn) {606 childFrameSession.dispose();607 return;608 } // However, sometimes we get detachedFromTarget before frameAttached.609 // In this case we don't know wheter this is a remote frame detach,610 // or just a remote -> local transition. In the latter case, frameAttached611 // is already inflight, so let's make a safe roundtrip to ensure it arrives.612 this._client.send('Page.enable').catch(e => null).then(() => {613 // Child was not swapped in - that means frameAttached did not happen and614 // this is remote detach rather than remote -> local swap.615 if (!childFrameSession._swappedIn) this._page._frameManager.frameDetached(event.targetId);616 childFrameSession.dispose();617 });618 }619 _onWindowOpen(event) {620 this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);621 }622 async _onConsoleAPI(event) {623 if (event.executionContextId === 0) {624 // DevTools protocol stores the last 1000 console messages. These625 // messages are always reported even for removed execution contexts. In626 // this case, they are marked with executionContextId = 0 and are627 // reported upon enabling Runtime agent.628 //629 // Ignore these messages since:630 // - there's no execution context we can use to operate with message631 // arguments632 // - these messages are reported before Playwright clients can subscribe633 // to the 'console'634 // page event.635 //636 // @see https://github.com/GoogleChrome/puppeteer/issues/3865637 return;638 }639 const context = this._contextIdToContext.get(event.executionContextId);640 if (!context) return;641 const values = event.args.map(arg => context.createHandle(arg));642 this._page._addConsoleMessage(event.type, values, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));643 }644 async _initBinding(binding) {645 await Promise.all([this._client.send('Runtime.addBinding', {646 name: binding.name647 }), this._client.send('Page.addScriptToEvaluateOnNewDocument', {648 source: binding.source649 })]);650 }651 async _onBindingCalled(event) {652 const pageOrError = await this._crPage.pageOrError();653 if (!(pageOrError instanceof Error)) {654 const context = this._contextIdToContext.get(event.executionContextId);655 if (context) await this._page._onBindingCalled(event.payload, context);656 }657 }658 _onDialog(event) {659 if (!this._page._frameManager.frame(this._targetId)) return; // Our frame/subtree may be gone already.660 this._page.emit(_page.Page.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {661 await this._client.send('Page.handleJavaScriptDialog', {662 accept,663 promptText664 });665 }, event.defaultPrompt));666 }667 _handleException(exceptionDetails) {668 this._page.firePageError((0, _crProtocolHelper.exceptionToError)(exceptionDetails));669 }670 async _onTargetCrashed() {671 this._client._markAsCrashed();672 this._page._didCrash();673 }674 _onLogEntryAdded(event) {675 const {676 level,677 text,678 args,679 source,680 url,681 lineNumber682 } = event.entry;683 if (args) args.map(arg => (0, _crProtocolHelper.releaseObject)(this._client, arg.objectId));684 if (source !== 'worker') {685 const location = {686 url: url || '',687 lineNumber: lineNumber || 0,688 columnNumber: 0689 };690 this._page._addConsoleMessage(level, [], location, text);691 }692 }693 async _onFileChooserOpened(event) {694 const frame = this._page._frameManager.frame(event.frameId);695 if (!frame) return;696 let handle;697 try {698 const utilityContext = await frame._utilityContext();699 handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);700 } catch (e) {701 // During async processing, frame/context may go away. We should not throw.702 return;703 }704 await this._page._onFileChooserOpened(handle);705 }706 _willBeginDownload() {707 const originPage = this._crPage._initializedPage;708 if (!originPage) {709 // Resume the page creation with an error. The page will automatically close right710 // after the download begins.711 this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));712 }713 }714 _onScreencastFrame(payload) {715 this._page.throttleScreencastFrameAck(() => {716 this._client.send('Page.screencastFrameAck', {717 sessionId: payload.sessionId718 }).catch(() => {});...
ffPage.js
Source:ffPage.js
...210 const context = this._contextIdToContext.get(event.executionContextId);211 if (context) await this._page._onBindingCalled(event.payload, context);212 }213 }214 async _onFileChooserOpened(payload) {215 const {216 executionContextId,217 element218 } = payload;219 const context = this._contextIdToContext.get(executionContextId);220 if (!context) return;221 const handle = context.createHandle(element).asElement();222 await this._page._onFileChooserOpened(handle);223 }224 async _onWorkerCreated(event) {225 const workerId = event.workerId;226 const worker = new _page.Worker(this._page, event.url);227 const workerSession = new _ffConnection.FFSession(this._session._connection, workerId, message => {228 this._session.send('Page.sendMessageToWorker', {229 frameId: event.frameId,230 workerId: workerId,231 message: JSON.stringify(message)232 }).catch(e => {233 workerSession.dispatchMessage({234 id: message.id,235 method: '',236 params: {},...
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.click('input[type="file"]');7 const fileChooser = await page.waitForEvent('filechooser');8 console.log(fileChooser);9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.click('input[type="file"]');17 const fileChooser = await page._onFileChooserOpened();18 console.log(fileChooser);19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await page.click('input[type="file"]');27 const fileChooser = await page._onFileChooserOpened();28 console.log(fileChooser);29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 await page.click('input[type="file"]');37 const fileChooser = await page._onFileChooserOpened();38 console.log(fileChooser);39 await browser.close();40})();
Using AI Code Generation
1const {chromium} = require('playwright');2const path = require('path')3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page._onFileChooserOpened(() => {7 console.log('File Chooser opened')8 });9 await page.click('text=Try it');10 await page.waitForTimeout(1000);11 const frame = page.frame({name:'iframeResult'});12 await frame.setInputFiles('input[type=file]', path.join(__dirname, 'test.txt'));13 await page.waitForTimeout(1000);14 await browser.close();15})();
Using AI Code Generation
1const {chromium} = require('playwright');2const {helper} = require('playwright/lib/helper');3const {BrowserContext} = require('playwright/lib/server/browserContext');4const {Page} = require('playwright/lib/server/page');5const {ElementHandle} = require('playwright/lib/server/elementHandler');6(async () => {7 const browser = await chromium.launch();8 const context = await browser.newContext();9 const page = await context.newPage();10 await page.click('#main > div.w3-main.w3-content > div > div:nth-child(2) > div > div > div > label > input');11 const fileChooser = await page.waitForEvent('filechooser');12 await fileChooser.setFiles('C:\\test\\testfile.txt');13 await browser.close();14})();15const {helper} = require('playwright/lib/helper');16const {BrowserContext} = require('playwright/lib/server/browserContext');17const {Page} = require('playwright/lib/server/page');18const {ElementHandle} = require('playwright/lib/server/elementHandler');19helper._onFileChooserOpened = function (fileChooser) {20 const {context, page, element} = fileChooser;21 if (context._pageBindings.has('filechooser'))22 context._pageBindings.get('filechooser')(fileChooser);23 if (page._pageBindings.has('filechooser'))24 page._pageBindings.get('filechooser')(fileChooser);25 if (element._pageBindings.has('filechooser'))26 element._pageBindings.get('filechooser')(fileChooser);27};28const {helper} = require('playwright/lib/helper');29const {BrowserContext} = require('playwright/lib/server/browserContext');30const {Page} = require('playwright/lib/server/page');31const {ElementHandle} = require('playwright/lib/server/elementHandler');32BrowserContext.prototype._onFileChooserOpened = function (fileChooser) {33 helper._onFileChooserOpened(fileChooser);34};35const {helper} = require('playwright/lib/helper');36const {BrowserContext} = require('playwright/lib/server/browserContext');37const {Page} = require('playwright/lib/server/page');38const {ElementHandle} = require
Using AI Code Generation
1const { _onFileChooserOpened } = require('playwright/lib/server/chromium/crBrowser');2const fs = require('fs');3const fileChooserHandler = async (fileChooser) => {4 console.log('File Chooser opened');5 await fileChooser.setFiles('test.txt');6 await fileChooser.element().click();7 await fileChooser.element().evaluate(node => node.click());8 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('change', { bubbles: true })));9 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('input', { bubbles: true })));10 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('blur', { bubbles: true })));11 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('focusout', { bubbles: true })));12 fs.writeFileSync('test.txt', 'Test');13 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('change', { bubbles: true })));14 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('input', { bubbles: true })));15 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('blur', { bubbles: true })));16 await fileChooser.element().evaluate(node => node.dispatchEvent(new Event('focusout', { bubbles: true })));17};18_onFileChooserOpened(fileChooserHandler);19module.exports = {20 use: {21 viewport: { width: 1280, height: 720 },22 launchOptions: {
Using AI Code Generation
1const { _onFileChooserOpened } = require('playwright/lib/server/chromium/crBrowser');2_onFileChooserOpened.call(browser, () => {3});4const { _onFileChooserOpened } = require('playwright/lib/server/chromium/crBrowser');5_onFileChooserOpened.call(browser, () => {6});
Using AI Code Generation
1const { _onFileChooserOpened } = require('playwright/lib/server/chromium/crBrowser');2_onFileChooserOpened = async (event, fileChooser) => {3 await fileChooser.setFiles('C:\\Users\\Downloads\\test.txt');4};5const {chromium} = require('playwright');6const browser = await chromium.launch({ headless: false });7const context = await browser.newContext();8const page = await context.newPage();9await page.click('iframe');10await page.click('input[type="file"]');11const {chromium} = require('playwright');12const browser = await chromium.launch({ headless: false });13const context = await browser.newContext();14const page = await context.newPage();15await page.click('iframe');16await page.click('input[type="file"]');17await page.waitForTimeout(5000);18await page.screenshot({ path: `screenshot.png` });19const {chromium} = require('playwright');20const browser = await chromium.launch({ headless: false });21const context = await browser.newContext();22const page = await context.newPage();23await page.click('iframe');24await page.click('input[type="file"]');25await page.waitForTimeout(5000);26await page.screenshot({ path: `screenshot.png` });27await page.close();28await browser.close();29const {chromium} = require('playwright');30const browser = await chromium.launch({ headless: false });31const context = await browser.newContext();32const page = await context.newPage();33await page.click('iframe');34await page.click('input[type="file"]');35await page.waitForTimeout(5000);36await page.screenshot({ path: `screenshot.png` });37await page.close();38await browser.close();39await context.close();40const {chromium} = require('
Using AI Code Generation
1const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");2_onFileChooserOpened.call(page, "file1.png", "file2.png");3const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");4_onFileChooserOpened.call(page, "file1.png", "file2.png");5const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");6_onFileChooserOpened.call(page, "file1.png", "file2.png");7const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");8_onFileChooserOpened.call(page, "file1.png", "file2.png");9const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");10_onFileChooserOpened.call(page, "file1.png", "file2.png");11const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");12_onFileChooserOpened.call(page, "file1.png", "file2.png");13const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");14_onFileChooserOpened.call(page, "file1.png", "file2.png");15const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");16_onFileChooserOpened.call(page, "file1.png", "file2.png");17const { _onFileChooserOpened } = require("playwright/lib/server/chromium/crPage");18_onFileChooserOpened.call(page, "file1.png", "file2.png");19const { _onFileChooserOpened } = require("playwright/lib/server
Using AI Code Generation
1const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');2_onFileChooserOpened(fileChooser, async () => {3 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');4});5const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');6_onFileChooserOpened(fileChooser, async () => {7 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');8});9const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');10_onFileChooserOpened(fileChooser, async () => {11 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');12});13const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');14_onFileChooserOpened(fileChooser, async () => {15 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');16});17const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');18_onFileChooserOpened(fileChooser, async () => {19 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');20});21const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');22_onFileChooserOpened(fileChooser, async () => {23 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');24});25const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');26_onFileChooserOpened(fileChooser, async () => {27 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');28});29const { _onFileChooserOpened } = require('playwright/lib/server/chromium/chromium');30_onFileChooserOpened(fileChooser, async () => {31 await fileChooser.setFiles('C:\\Users\\Downloads\\example.pdf');32});33const { _onFileChooserOpened } = require
Using AI Code Generation
1const playwright = require('playwright');2const path = require('path');3(async () => {4 const browser = await playwright.chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 page._onFileChooserOpened = async (fileChooser) => {8 await fileChooser.setFiles(path.join(__dirname, 'test.pdf'));9 };10 await page.click('#main > form > input[type="file"]');11 await page.waitForTimeout(1000);12 await page.screenshot({ path: 'test.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!!