Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js  
...252  async getBoundingBox(handle) {253    return this._sessionForHandle(handle)._getBoundingBox(handle);254  }255  async scrollRectIntoViewIfNeeded(handle, rect) {256    return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);257  }258  async setScreencastOptions(options) {259    if (options) {260      await this._mainFrameSession._startScreencast(this, {261        format: 'jpeg',262        quality: options.quality,263        maxWidth: options.width,264        maxHeight: options.height265      });266    } else {267      await this._mainFrameSession._stopScreencast(this);268    }269  }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;...dom.js
Source:dom.js  
...363      }364    )365    await this._page._doSlowMo()366  }367  async _scrollRectIntoViewIfNeeded(rect) {368    return await this._page._delegate.scrollRectIntoViewIfNeeded(this, rect)369  }370  async _waitAndScrollIntoViewIfNeeded(progress) {371    while (progress.isRunning()) {372      assertDone(373        throwRetargetableDOMError(374          await this._waitForDisplayedAtStablePosition(375            progress,376            false,377            /* force */378            false379            /* waitForEnabled */380          )381        )382      )383      progress.throwIfAborted() // Avoid action that has side-effects.384      const result = throwRetargetableDOMError(385        await this._scrollRectIntoViewIfNeeded()386      )387      if (result === 'error:notvisible') continue388      assertDone(result)389      return390    }391  }392  async scrollIntoViewIfNeeded(metadata, options = {}) {393    const controller = new _progress.ProgressController(metadata, this)394    return controller.run(395      (progress) => this._waitAndScrollIntoViewIfNeeded(progress),396      this._page._timeoutSettings.timeout(options)397    )398  }399  async _clickablePoint() {400    const intersectQuadWithViewport = (quad) => {401      return quad.map((point) => ({402        x: Math.min(Math.max(point.x, 0), metrics.width),403        y: Math.min(Math.max(point.y, 0), metrics.height)404      }))405    }406    const computeQuadArea = (quad) => {407      // Compute sum of all directed areas of adjacent triangles408      // https://en.wikipedia.org/wiki/Polygon#Simple_polygons409      let area = 0410      for (let i = 0; i < quad.length; ++i) {411        const p1 = quad[i]412        const p2 = quad[(i + 1) % quad.length]413        area += (p1.x * p2.y - p2.x * p1.y) / 2414      }415      return Math.abs(area)416    }417    const [quads, metrics] = await Promise.all([418      this._page._delegate.getContentQuads(this),419      this._page420        .mainFrame()421        ._utilityContext()422        .then((utility) =>423          utility.evaluate(() => ({424            width: innerWidth,425            height: innerHeight426          }))427        )428    ])429    if (!quads || !quads.length) return 'error:notvisible' // Allow 1x1 elements. Compensate for rounding errors by comparing with 0.99 instead.430    const filtered = quads431      .map((quad) => intersectQuadWithViewport(quad))432      .filter((quad) => computeQuadArea(quad) > 0.99)433    if (!filtered.length) return 'error:notinviewport' // Return the middle point of the first quad.434    const result = {435      x: 0,436      y: 0437    }438    for (const point of filtered[0]) {439      result.x += point.x / 4440      result.y += point.y / 4441    }442    compensateHalfIntegerRoundingError(result)443    return result444  }445  async _offsetPoint(offset) {446    const [box, border] = await Promise.all([447      this.boundingBox(),448      this.evaluateInUtility(449        ([injected, node]) => injected.getElementBorderWidth(node),450        {}451      ).catch((e) => {})452    ])453    if (!box || !border) return 'error:notvisible'454    if (border === 'error:notconnected') return border // Make point relative to the padding box to align with offsetX/offsetY.455    return {456      x: box.x + border.left + offset.x,457      y: box.y + border.top + offset.y458    }459  }460  async _retryPointerAction(461    progress,462    actionName,463    waitForEnabled,464    action,465    options466  ) {467    let retry = 0 // We progressively wait longer between retries, up to 500ms.468    const waitTime = [0, 20, 100, 100, 500] // By default, we scroll with protocol method to reveal the action point.469    // However, that might not work to scroll from under position:sticky elements470    // that overlay the target element. To fight this, we cycle through different471    // scroll alignments. This works in most scenarios.472    const scrollOptions = [473      undefined,474      {475        block: 'end',476        inline: 'end'477      },478      {479        block: 'center',480        inline: 'center'481      },482      {483        block: 'start',484        inline: 'start'485      }486    ]487    while (progress.isRunning()) {488      if (retry) {489        progress.log(490          `retrying ${actionName} action${491            options.trial ? ' (trial run)' : ''492          }, attempt #${retry}`493        )494        const timeout = waitTime[Math.min(retry - 1, waitTime.length - 1)]495        if (timeout) {496          progress.log(`  waiting ${timeout}ms`)497          const result = await this.evaluateInUtility(498            ([injected, node, timeout]) =>499              new Promise((f) => setTimeout(f, timeout)),500            timeout501          )502          if (result === 'error:notconnected') return result503        }504      } else {505        progress.log(506          `attempting ${actionName} action${507            options.trial ? ' (trial run)' : ''508          }`509        )510      }511      const forceScrollOptions = scrollOptions[retry % scrollOptions.length]512      const result = await this._performPointerAction(513        progress,514        actionName,515        waitForEnabled,516        action,517        forceScrollOptions,518        options519      )520      ++retry521      if (result === 'error:notvisible') {522        if (options.force) throw new Error('Element is not visible')523        progress.log('  element is not visible')524        continue525      }526      if (result === 'error:notinviewport') {527        if (options.force) throw new Error('Element is outside of the viewport')528        progress.log('  element is outside of the viewport')529        continue530      }531      if (typeof result === 'object' && 'hitTargetDescription' in result) {532        if (options.force)533          throw new Error(534            `Element does not receive pointer events, ${result.hitTargetDescription} intercepts them`535          )536        progress.log(537          `  ${result.hitTargetDescription} intercepts pointer events`538        )539        continue540      }541      return result542    }543    return 'done'544  }545  async _performPointerAction(546    progress,547    actionName,548    waitForEnabled,549    action,550    forceScrollOptions,551    options552  ) {553    const { force = false, position } = options554    if (options.__testHookBeforeStable) await options.__testHookBeforeStable()555    const result = await this._waitForDisplayedAtStablePosition(556      progress,557      force,558      waitForEnabled559    )560    if (result !== 'done') return result561    if (options.__testHookAfterStable) await options.__testHookAfterStable()562    progress.log('  scrolling into view if needed')563    progress.throwIfAborted() // Avoid action that has side-effects.564    if (forceScrollOptions) {565      const scrolled = await this.evaluateInUtility(566        ([injected, node, options]) => {567          if (568            node.nodeType === 1569            /* Node.ELEMENT_NODE */570          )571            node.scrollIntoView(options)572        },573        forceScrollOptions574      )575      if (scrolled === 'error:notconnected') return scrolled576    } else {577      const scrolled = await this._scrollRectIntoViewIfNeeded(578        position579          ? {580              x: position.x,581              y: position.y,582              width: 0,583              height: 0584            }585          : undefined586      )587      if (scrolled !== 'done') return scrolled588    }589    progress.log('  done scrolling')590    const maybePoint = position591      ? await this._offsetPoint(position)...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('input[name="q"]');6  await page.keyboard.type('playwright');7  await page.keyboard.press('Enter');8  await page.waitForNavigation();9  await page.click('text=Playwright - Node.js library to automate Chromium, Firefox and WebKit with a single API');10  await page.waitForSelector('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API');11  await page.screenshot({ path: `example.png` });12  await browser.close();13})();Using AI Code Generation
1const { ElementHandle } = require('playwright/lib/cjs/puppeteer/common/JSHandle');2const { helper } = require('playwright/lib/cjs/puppeteer/common/helper');3const { assert } = require('playwright/lib/cjs/puppeteer/common/assert');4const { ScrollBehavior } = require('playwright/lib/cjs/puppeteer/common/USKeyboardLayout');5const { assertMaxArguments } = require('playwright/lib/cjs/puppeteer/common/helper');6ElementHandle.prototype.scrollRectIntoViewIfNeeded = async function(rect, options = {}) {7  assertMaxArguments(arguments.length, 2);8  assert(rect, 'Missing rect');9  assert(typeof rect === 'object', 'rect must be an object');10  assert(rect.x !== undefined, 'Missing rect.x');11  assert(rect.y !== undefined, 'Missing rect.y');12  assert(rect.width !== undefined, 'Missing rect.width');13  assert(rect.height !== undefined, 'Missing rect.height');14  assert(typeof rect.x === 'number', 'rect.x must be a number');15  assert(typeof rect.y === 'number', 'rect.y must be a number');16  assert(typeof rect.width === 'number', 'rect.width must be a number');17  assert(typeof rect.height === 'number', 'rect.height must be a number');18  if (options.behavior === undefined)19    options.behavior = 'auto';20  assert(typeof options.behavior === 'string', 'options.behavior must be a string');21  assert(options.behavior === 'auto' || options.behavior === 'instant' || options.behavior === 'smooth', 'options.behavior: expected one of (auto, instant, smooth)');22  const result = await this._scrollRectIntoViewIfNeeded({23  });24  helper.releaseObject(result);25};26const { chromium } = require('playwright');27(async () => {28  const browser = await chromium.launch({ headless: false });29  const context = await browser.newContext();30  const page = await context.newPage();31  await page.waitForSelector('input[name="q"]');32  const searchInput = await page.$('input[name="q"]');Using AI Code Generation
1const element = await page.$('#elementId');2const internalElement = element.asElement();3await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});4const element = await page.$('#elementId');5const internalElement = element.asElement();6await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});7const element = await page.$('#elementId');8const internalElement = element.asElement();9await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});10const element = await page.$('#elementId');11const internalElement = element.asElement();12await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});13const element = await page.$('#elementId');14const internalElement = element.asElement();15await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});16const element = await page.$('#elementId');17const internalElement = element.asElement();18await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});19const element = await page.$('#elementId');20const internalElement = element.asElement();21await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});22const element = await page.$('#elementId');23const internalElement = element.asElement();24await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0Using AI Code Generation
1const element = await page.$('#elementId');2const internalElement = element.asElement();3await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});4const element = await page.$('#elementId');5const internalElement = element.asElement();6await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});7const element = await page.$('#elementId');8const internalElement = element.asElement();9await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});10const element = await page.$('#elementId');11const internalElement = element.asElement();12await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});13const element = await page.$('#elementId');14const internalElement = element.asElement();15await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});16const element = await page.$('#elementId');17const internalElement = element.asElement();18await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});19const element = await page.$('#elementId');20const internalElement = element.asElement();21await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0, height: 0});22const element = await page.$('#elementId');23const internalElement = element.asElement();24await internalElement._scrollRectIntoViewIfNeeded({x: 0, y: 0, width: 0Using AI Code Generation
1    const { _scrollRectIntoViewIfNeeded } = require('playwright/lib/server/chromium/crPage');2    const { chromium } = require('playwright');3    (async () => {4      const browser = await chromium.launch({ headless: false });5      const context = await browser.newContext();6      const page = await context.newPage();7      await page.waitForSelector('.navbar__inner');8      await page.waitForTimeout(2000);9      const element = await page.$('.navbar__inner');10      await _scrollRectIntoViewIfNeeded(page, await element.boundingBox());11      await page.waitForTimeout(2000);12      await browser.close();13    })();Using AI Code Generation
1const { _scrollRectIntoViewIfNeeded } = require('playwright/lib/page');2const { getBoundingBox } = require('playwright/lib/elementHandle');3(asyn () => {4  cnst browser = await chromium.launch({ healss:false });5  cons page = await brwser.newPage();6  await page.waitForSelector('iframe');7  cont frame = page.frams()[1];8  awaitframe.waitForSelector('input[type=checkbox]');9  const checkbox = await frame.$('input[type=checkbox]');10  await (page, checkbox, await getBoundingBox(checkbox));11  await checkbox.click();12  await browser.close();13})();Using AI Code Generation
1const { _scrollRectIntoViewIfNeeded } = require('playwright/lib/page');2const { getBoundingBox } = require('playwright/lib/elementHandle');3(async () => {4  const browser = await chromium.launch({ headless: false });5  const page = await browser.newPage();6  await page.waitForSelector('iframe');7  const frame = page.frames()[1];8  await frame.waitForSelector('input[type=checkbox]');9  const checkbox = await frame.$('input[type=checkbox]');10  await _scrollRectIntoViewIfNeeded(page, checkbox, await getBoundingBox(checkbox));11  await checkbox.click();12  await browser.close();13})();Using AI Code Generation
1const { Internal } = require('playwright/lib/server/chromium/crPage');2const { ElementHandle } = require('playwright/lib/server/dom');3ElementHandle.prototype.scrollIntoViewIfNeeded = async function (options = {}) {4  const internal = new Internal(this._context);5  await internal._scrollRectIntoViewIfNeeded(this._remoteObject.objectId, options);6};7const { chromium } = require('playwright');8(async () => {9  const browser = await chromium.launch({ headless: false });10  const page = await browser.newPage();11  const element = await page.$('text=Docs');12  await element.scrollIntoViewIfNeeded();13  await browser.close();14})();Using AI Code Generation
1const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');2const element = await page.$('div');3await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);4const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');5const element = await page.$('div');6await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);7const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');8const element = await page.$('div');9await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);10const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');11const element = await page.$('div');12await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);13const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');14const element = await page.$('div');15await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);16const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');17const element = await page.$('div');18await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);19const { _scrollRectIntoViewIfNeeded } = require('playwright-core/lib/server/chromium/crPage');20const element = await page.$('div');21await _scrollRectIntoViewIfNeeded.call(page, element, 0, 0, 0, 0);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!!
