Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js
...270 rafCountForStablePosition() {271 return 1;272 }273 async getContentQuads(handle) {274 return this._sessionForHandle(handle)._getContentQuads(handle);275 }276 async setInputFiles(handle, files) {277 await handle.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), files);278 }279 async adoptElementHandle(handle, to) {280 return this._sessionForHandle(handle)._adoptElementHandle(handle, to);281 }282 async getAccessibilityTree(needle) {283 return (0, _crAccessibility.getAccessibilityTree)(this._mainFrameSession._client, needle);284 }285 async inputActionEpilogue() {286 await this._mainFrameSession._client.send('Page.enable').catch(e => {});287 }288 async pdf(options) {289 return this._pdf.generate(options);290 }291 coverage() {292 return this._coverage;293 }294 async getFrameElement(frame) {295 let parent = frame.parentFrame();296 if (!parent) throw new Error('Frame has been detached.');297 const parentSession = this._sessionForFrame(parent);298 const {299 backendNodeId300 } = await parentSession._client.send('DOM.getFrameOwner', {301 frameId: frame._id302 }).catch(e => {303 if (e instanceof Error && e.message.includes('Frame with the given id was not found.')) (0, _stackTrace.rewriteErrorMessage)(e, 'Frame has been detached.');304 throw e;305 });306 parent = frame.parentFrame();307 if (!parent) throw new Error('Frame has been detached.');308 return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());309 }310}311exports.CRPage = CRPage;312class FrameSession {313 // Marks the oopif session that remote -> local transition has happened in the parent.314 // See Target.detachedFromTarget handler for details.315 constructor(crPage, client, targetId, parentSession) {316 this._client = void 0;317 this._crPage = void 0;318 this._page = void 0;319 this._networkManager = void 0;320 this._contextIdToContext = new Map();321 this._eventListeners = [];322 this._targetId = void 0;323 this._firstNonInitialNavigationCommittedPromise = void 0;324 this._firstNonInitialNavigationCommittedFulfill = () => {};325 this._firstNonInitialNavigationCommittedReject = e => {};326 this._windowId = void 0;327 this._swappedIn = false;328 this._videoRecorder = null;329 this._screencastId = null;330 this._screencastClients = new Set();331 this._client = client;332 this._crPage = crPage;333 this._page = crPage._page;334 this._targetId = targetId;335 this._networkManager = new _crNetworkManager.CRNetworkManager(client, this._page, parentSession ? parentSession._networkManager : null);336 this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {337 this._firstNonInitialNavigationCommittedFulfill = f;338 this._firstNonInitialNavigationCommittedReject = r;339 });340 client.once(_crConnection.CRSessionEvents.Disconnected, () => {341 this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));342 });343 }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(() => {});719 });720 const buffer = Buffer.from(payload.data, 'base64');721 this._page.emit(_page.Page.Events.ScreencastFrame, {722 buffer,723 timestamp: payload.metadata.timestamp,724 width: payload.metadata.deviceWidth,725 height: payload.metadata.deviceHeight726 });727 }728 async _createVideoRecorder(screencastId, options) {729 (0, _utils.assert)(!this._screencastId);730 const ffmpegPath = _registry.registry.findExecutable('ffmpeg').executablePathOrDie(this._page._browserContext._browser.options.sdkLanguage);731 this._videoRecorder = await _videoRecorder.VideoRecorder.launch(this._crPage._page, ffmpegPath, options);732 this._screencastId = screencastId;733 }734 async _startVideoRecording(options) {735 const screencastId = this._screencastId;736 (0, _utils.assert)(screencastId);737 this._page.once(_page.Page.Events.Close, () => this._stopVideoRecording().catch(() => {}));738 const gotFirstFrame = new Promise(f => this._client.once('Page.screencastFrame', f));739 await this._startScreencast(this._videoRecorder, {740 format: 'jpeg',741 quality: 90,742 maxWidth: options.width,743 maxHeight: options.height744 }); // Wait for the first frame before reporting video to the client.745 gotFirstFrame.then(() => {746 this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());747 });748 }749 async _stopVideoRecording() {750 if (!this._screencastId) return;751 const screencastId = this._screencastId;752 this._screencastId = null;753 const recorder = this._videoRecorder;754 this._videoRecorder = null;755 await this._stopScreencast(recorder);756 await recorder.stop().catch(() => {}); // Keep the video artifact in the map utntil encoding is fully finished, if the context757 // starts closing before the video is fully written to disk it will wait for it.758 const video = this._crPage._browserContext._browser._takeVideo(screencastId);759 video === null || video === void 0 ? void 0 : video.reportFinished();760 }761 async _startScreencast(client, options = {}) {762 this._screencastClients.add(client);763 if (this._screencastClients.size === 1) await this._client.send('Page.startScreencast', options);764 }765 async _stopScreencast(client) {766 this._screencastClients.delete(client);767 if (!this._screencastClients.size) await this._client._sendMayFail('Page.stopScreencast');768 }769 async _updateExtraHTTPHeaders(initial) {770 const headers = network.mergeHeaders([this._crPage._browserContext._options.extraHTTPHeaders, this._page._state.extraHTTPHeaders]);771 if (!initial || headers.length) await this._client.send('Network.setExtraHTTPHeaders', {772 headers: (0, _utils.headersArrayToObject)(headers, false773 /* lowerCase */774 )775 });776 }777 async _updateGeolocation(initial) {778 const geolocation = this._crPage._browserContext._options.geolocation;779 if (!initial || geolocation) await this._client.send('Emulation.setGeolocationOverride', geolocation || {});780 }781 async _updateOffline(initial) {782 const offline = !!this._crPage._browserContext._options.offline;783 if (!initial || offline) await this._networkManager.setOffline(offline);784 }785 async _updateHttpCredentials(initial) {786 const credentials = this._crPage._browserContext._options.httpCredentials || null;787 if (!initial || credentials) await this._networkManager.authenticate(credentials);788 }789 async _updateViewport() {790 if (this._crPage._browserContext._browser.isClank()) return;791 (0, _utils.assert)(this._isMainFrame());792 const options = this._crPage._browserContext._options;793 const emulatedSize = this._page._state.emulatedSize;794 if (emulatedSize === null) return;795 const viewportSize = emulatedSize.viewport;796 const screenSize = emulatedSize.screen;797 const isLandscape = viewportSize.width > viewportSize.height;798 const promises = [this._client.send('Emulation.setDeviceMetricsOverride', {799 mobile: !!options.isMobile,800 width: viewportSize.width,801 height: viewportSize.height,802 screenWidth: screenSize.width,803 screenHeight: screenSize.height,804 deviceScaleFactor: options.deviceScaleFactor || 1,805 screenOrientation: isLandscape ? {806 angle: 90,807 type: 'landscapePrimary'808 } : {809 angle: 0,810 type: 'portraitPrimary'811 }812 })];813 if (this._windowId) {814 let insets = {815 width: 0,816 height: 0817 };818 if (this._crPage._browserContext._browser.options.headful) {819 // TODO: popup windows have their own insets.820 insets = {821 width: 24,822 height: 88823 };824 if (process.platform === 'win32') insets = {825 width: 16,826 height: 88827 };else if (process.platform === 'linux') insets = {828 width: 8,829 height: 85830 };else if (process.platform === 'darwin') insets = {831 width: 2,832 height: 80833 };834 if (this._crPage._browserContext.isPersistentContext()) {835 // FIXME: Chrome bug: OOPIF router is confused when hit target is836 // outside browser window.837 // Account for the infobar here to work around the bug.838 insets.height += 46;839 }840 }841 promises.push(this.setWindowBounds({842 width: viewportSize.width + insets.width,843 height: viewportSize.height + insets.height844 }));845 }846 await Promise.all(promises);847 }848 async windowBounds() {849 const {850 bounds851 } = await this._client.send('Browser.getWindowBounds', {852 windowId: this._windowId853 });854 return bounds;855 }856 async setWindowBounds(bounds) {857 return await this._client.send('Browser.setWindowBounds', {858 windowId: this._windowId,859 bounds860 });861 }862 async _updateEmulateMedia(initial) {863 if (this._crPage._browserContext._browser.isClank()) return;864 const colorScheme = this._page._state.colorScheme === null ? '' : this._page._state.colorScheme;865 const reducedMotion = this._page._state.reducedMotion === null ? '' : this._page._state.reducedMotion;866 const forcedColors = this._page._state.forcedColors === null ? '' : this._page._state.forcedColors;867 const features = [{868 name: 'prefers-color-scheme',869 value: colorScheme870 }, {871 name: 'prefers-reduced-motion',872 value: reducedMotion873 }, {874 name: 'forced-colors',875 value: forcedColors876 }]; // Empty string disables the override.877 await this._client.send('Emulation.setEmulatedMedia', {878 media: this._page._state.mediaType || '',879 features880 });881 }882 async _updateRequestInterception() {883 await this._networkManager.setRequestInterception(this._page._needsRequestInterception());884 }885 async _setFileChooserIntercepted(enabled) {886 await this._client.send('Page.setInterceptFileChooserDialog', {887 enabled888 }).catch(e => {}); // target can be closed.889 }890 async _evaluateOnNewDocument(source, world) {891 const worldName = world === 'utility' ? UTILITY_WORLD_NAME : undefined;892 await this._client.send('Page.addScriptToEvaluateOnNewDocument', {893 source,894 worldName895 });896 }897 async _getContentFrame(handle) {898 const nodeInfo = await this._client.send('DOM.describeNode', {899 objectId: handle._objectId900 });901 if (!nodeInfo || typeof nodeInfo.node.frameId !== 'string') return null;902 return this._page._frameManager.frame(nodeInfo.node.frameId);903 }904 async _getOwnerFrame(handle) {905 // document.documentElement has frameId of the owner frame.906 const documentElement = await handle.evaluateHandle(node => {907 const doc = node;908 if (doc.documentElement && doc.documentElement.ownerDocument === doc) return doc.documentElement;909 return node.ownerDocument ? node.ownerDocument.documentElement : null;910 });911 if (!documentElement) return null;912 if (!documentElement._objectId) return null;913 const nodeInfo = await this._client.send('DOM.describeNode', {914 objectId: documentElement._objectId915 });916 const frameId = nodeInfo && typeof nodeInfo.node.frameId === 'string' ? nodeInfo.node.frameId : null;917 documentElement.dispose();918 return frameId;919 }920 async _getBoundingBox(handle) {921 const result = await this._client._sendMayFail('DOM.getBoxModel', {922 objectId: handle._objectId923 });924 if (!result) return null;925 const quad = result.model.border;926 const x = Math.min(quad[0], quad[2], quad[4], quad[6]);927 const y = Math.min(quad[1], quad[3], quad[5], quad[7]);928 const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;929 const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;930 const position = await this._framePosition();931 if (!position) return null;932 return {933 x: x + position.x,934 y: y + position.y,935 width,936 height937 };938 }939 async _framePosition() {940 const frame = this._page._frameManager.frame(this._targetId);941 if (!frame) return null;942 if (frame === this._page.mainFrame()) return {943 x: 0,944 y: 0945 };946 const element = await frame.frameElement();947 const box = await element.boundingBox();948 return box;949 }950 async _scrollRectIntoViewIfNeeded(handle, rect) {951 return await this._client.send('DOM.scrollIntoViewIfNeeded', {952 objectId: handle._objectId,953 rect954 }).then(() => 'done').catch(e => {955 if (e instanceof Error && e.message.includes('Node does not have a layout object')) return 'error:notvisible';956 if (e instanceof Error && e.message.includes('Node is detached from document')) return 'error:notconnected';957 throw e;958 });959 }960 async _getContentQuads(handle) {961 const result = await this._client._sendMayFail('DOM.getContentQuads', {962 objectId: handle._objectId963 });964 if (!result) return null;965 const position = await this._framePosition();966 if (!position) return null;967 return result.quads.map(quad => [{968 x: quad[0] + position.x,969 y: quad[1] + position.y970 }, {971 x: quad[2] + position.x,972 y: quad[3] + position.y973 }, {974 x: quad[4] + position.x,...
PageAgent.js
Source:PageAgent.js
...405 throw new Error('Object is not input!');406 const nsFiles = await Promise.all(files.map(filePath => File.createFromFileName(filePath)));407 unsafeObject.mozSetFileArray(nsFiles);408 }409 _getContentQuads({objectId, frameId}) {410 const frame = this._frameTree.frame(frameId);411 if (!frame)412 throw new Error('Failed to find frame with id = ' + frameId);413 const unsafeObject = frame.unsafeObject(objectId);414 if (!unsafeObject.getBoxQuads)415 throw new Error('RemoteObject is not a node');416 const quads = unsafeObject.getBoxQuads({relativeTo: this._frameTree.mainFrame().domWindow().document}).map(quad => {417 return {418 p1: {x: quad.p1.x, y: quad.p1.y},419 p2: {x: quad.p2.x, y: quad.p2.y},420 p3: {x: quad.p3.x, y: quad.p3.y},421 p4: {x: quad.p4.x, y: quad.p4.y},422 };423 });...
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 const contentQuads = await page._client.send('DOM.getContentQuads', {nodeId: 1});7 console.log(contentQuads);8 await browser.close();9})();10{ quads: [ [ 0, 0, 0, 0, 0, 0, 0, 0 ] ] }
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 const element = await page.$('text=Playwright');6 const quads = await page._client.send('DOM.getContentQuads', { nodeId: element._nodeId });7 console.log(quads);8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch({ headless: false });13 const page = await browser.newPage();14 const element = await page.$('text=Playwright');15 const model = await page._client.send('DOM.getBoxModel', { nodeId: element._nodeId });16 console.log(model);17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch({ headless: false });22 const page = await browser.newPage();23 const element = await page.$('text=Playwright');24 const tree = await page._client.send('DOM.getLayoutTree', { nodeId: element._nodeId });25 console.log(tree);26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch({ headless: false });31 const page = await browser.newPage();32 const element = await page.$('text=Playwright');33 const content = await page._client.send('DOM.getFullTextContent', { nodeId: element._nodeId });34 console.log(content);35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch({ headless: false });
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6const element = await page.$('text=Docs');7const quads = await element._getContentQuads();8console.log(quads);9await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13const browser = await chromium.launch();14const context = await browser.newContext();15const page = await context.newPage();16const element = await page.$('text=Docs');17const box = await element._getBoundingBox();18console.log(box);19await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23const browser = await chromium.launch();24const context = await browser.newContext();25const page = await context.newPage();26await page.waitForSelector('iframe');27const frame = await page.frames()[1];28await frame.waitForSelector('input[type="file"]');29const element = await frame.$('input[type="file"]');30await element._interceptFileChooser(async (fileChooser) => {31await fileChooser.setFiles('/path/to/file.txt');32});33await frame.click('input[type="submit"]');34await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38const browser = await chromium.launch();39const context = await browser.newContext();40const page = await context.newPage();41await page.waitForSelector('iframe');42const frame = await page.frames()[1];43await frame.waitForSelector('input[type="file"]');44const element = await frame.$('input[type="file"]');45await element._setFileInputFiles('/path/to/file.txt');46await frame.click('input[type="submit"]');47await browser.close();48})();49const { chromium } = require('playwright');50(async () => {
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.setContent(`<style>7 .box {8 width: 100px;9 height: 100px;10 background: red;11 }12 <div class="box"></div>`);13 const element = await page.$('.box');14 const quads = await element._getContentQuads();15 console.log(quads);16 await browser.close();17})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const elementHandle = await page.$('input[name="q"]');6 const quads = await elementHandle._getContentQuads();7 console.log(quads);8 await browser.close();9})();10[ [ { x: 16.5, y: 16.5 },11 { x: 16.5, y: 56.5 },12 { x: 223.5, y: 56.5 },13 { x: 223.5, y: 16.5 } ] ]
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.click('text=Search');6 const quads = await page._client.send('DOM.getContentQuads', {7 objectId: (await page.$('text=Search'))._remoteObject.objectId,8 });9 console.log(quads);10 await browser.close();11})();12{13 { x: 0, y: 0 },14 { x: 0, y: 0 },15 { x: 0, y: 0 },16 { x: 0, y: 0 }17 { x: 0, y: 0 },18 { x: 0, y: 0 },19 { x: 0, y: 0 },20 { x: 0, y: 0 }21 { x: 0, y: 0 },22 { x: 0, y: 0 },23 { x: 0, y: 0 },24 { x: 0, y: 0 }25 { x: 0, y: 0 },26 { x: 0, y: 0 },27 { x: 0, y: 0 },28 { x: 0, y: 0 }29}
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 elementHandle = await page.$('text=Get started');7 const quads = await page._client.send('DOM.getContentQuads', {8 });9 console.log(quads);10 await browser.close();11})();12{13}
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const input = await page.$('input');7 const quads = await page.evaluate(element => {8 const quads = element._getContentQuads();9 return quads;10 }, input);11 console.log(quads);12 await browser.close();13})();14 { x: 0, y: 0 },15 { x: 0, y: 0 },16 { x: 0, y: 0 },17 { x: 0, y: 0 }18 { x: 0, y: 0 },19 { x: 0, y: 0 },20 { x: 0, y: 0 },21 { x: 0, y: 0 }22const playwright = require('playwright');23(async () => {24 const browser = await playwright.chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 const input = await page.$('input');28 const quads = await page.evaluate(element => {29 const quads = element._getContentQuads();30 return quads;31 }, input);32 console.log(quads);33 for (const quad of quads) {34 const [p1, p2, p3, p4] = quad;35 const x = Math.min(p1.x, p2.x, p3.x, p4.x);36 const y = Math.min(p1.y, p2.y, p3.y, p4.y);
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 const handle = await page.$('text=Learn more');8 const quads = await handle._getContentQuads();9 console.log(quads);10 await browser.close();11})();12const playwright = require('playwright');13(async () => {14 const browser = await playwright.chromium.launch({15 });16 const context = await browser.newContext();17 const page = await context.newPage();18 const handle = await page.$('text=Learn more');19 const quads = await handle._getContentQuads();20 console.log(quads);21 await browser.close();22})();23const playwright = require('playwright');24(async () => {25 const browser = await playwright.chromium.launch({26 });27 const context = await browser.newContext();28 const page = await context.newPage();29 const handle = await page.$('text=Learn more');30 const quads = await handle._getContentQuads();31 console.log(quads);32 await browser.close();33})();34const playwright = require('playwright');35(async () => {36 const browser = await playwright.chromium.launch({37 });38 const context = await browser.newContext();39 const page = await context.newPage();
Using AI Code Generation
1const { _getContentQuads } = require('@playwright/test/lib/server/domSnapshot');2const { _getBoundingBox } = require('@playwright/test/lib/server/domSnapshot');3const element = document.querySelector('button');4const boundingBox = _getBoundingBox(_getContentQuads(element, false));5console.log(boundingBox);6const { test } = require('@playwright/test');7const { _getContentQuads } = require('@playwright/test/lib/server/domSnapshot');8const { _getBoundingBox } = require('@playwright/test/lib/server/domSnapshot');9test('test', async ({ page }) => {10 const boundingBox = await page.evaluate(() => {11 const element = document.querySelector('button');12 return _getBoundingBox(_getContentQuads(element, false));13 });14 console.log(boundingBox);15});
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!!