Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js  
...160    await this._forAllFrameSessions(frame => frame._initBinding(binding));161    await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source, false, {}).catch(e => {})));162  }163  async removeExposedBindings() {164    await this._forAllFrameSessions(frame => frame._removeExposedBindings());165  }166  async updateExtraHTTPHeaders() {167    await this._forAllFrameSessions(frame => frame._updateExtraHTTPHeaders(false));168  }169  async updateGeolocation() {170    await this._forAllFrameSessions(frame => frame._updateGeolocation(false));171  }172  async updateOffline() {173    await this._forAllFrameSessions(frame => frame._updateOffline(false));174  }175  async updateHttpCredentials() {176    await this._forAllFrameSessions(frame => frame._updateHttpCredentials(false));177  }178  async setEmulatedSize(emulatedSize) {179    (0, _utils.assert)(this._page._state.emulatedSize === emulatedSize);180    await this._mainFrameSession._updateViewport();181  }182  async bringToFront() {183    await this._mainFrameSession._client.send('Page.bringToFront');184  }185  async updateEmulateMedia() {186    await this._forAllFrameSessions(frame => frame._updateEmulateMedia(false));187  }188  async updateRequestInterception() {189    await this._forAllFrameSessions(frame => frame._updateRequestInterception());190  }191  async setFileChooserIntercepted(enabled) {192    await this._forAllFrameSessions(frame => frame.setFileChooserIntercepted(enabled));193  }194  async reload() {195    await this._mainFrameSession._client.send('Page.reload');196  }197  async _go(delta) {198    const history = await this._mainFrameSession._client.send('Page.getNavigationHistory');199    const entry = history.entries[history.currentIndex + delta];200    if (!entry) return false;201    await this._mainFrameSession._client.send('Page.navigateToHistoryEntry', {202      entryId: entry.id203    });204    return true;205  }206  goBack() {207    return this._go(-1);208  }209  goForward() {210    return this._go(+1);211  }212  async addInitScript(source, world = 'main') {213    await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(source, world));214  }215  async removeInitScripts() {216    await this._forAllFrameSessions(frame => frame._removeEvaluatesOnNewDocument());217  }218  async closePage(runBeforeUnload) {219    if (runBeforeUnload) await this._mainFrameSession._client.send('Page.close');else await this._browserContext._browser._closePage(this);220  }221  async setBackgroundColor(color) {222    await this._mainFrameSession._client.send('Emulation.setDefaultBackgroundColorOverride', {223      color224    });225  }226  async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {227    const {228      visualViewport229    } = await this._mainFrameSession._client.send('Page.getLayoutMetrics');230    if (!documentRect) {231      documentRect = {232        x: visualViewport.pageX + viewportRect.x,233        y: visualViewport.pageY + viewportRect.y,234        ..._helper.helper.enclosingIntSize({235          width: viewportRect.width / visualViewport.scale,236          height: viewportRect.height / visualViewport.scale237        })238      };239    } // When taking screenshots with documentRect (based on the page content, not viewport),240    // ignore current page scale.241    const clip = { ...documentRect,242      scale: viewportRect ? visualViewport.scale : 1243    };244    if (scale === 'css') {245      const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;246      clip.scale /= deviceScaleFactor;247    }248    progress.throwIfAborted();249    const result = await this._mainFrameSession._client.send('Page.captureScreenshot', {250      format,251      quality,252      clip,253      captureBeyondViewport: !fitsViewport254    });255    return Buffer.from(result.data, 'base64');256  }257  async getContentFrame(handle) {258    return this._sessionForHandle(handle)._getContentFrame(handle);259  }260  async getOwnerFrame(handle) {261    return this._sessionForHandle(handle)._getOwnerFrame(handle);262  }263  isElementHandle(remoteObject) {264    return remoteObject.subtype === 'node';265  }266  async getBoundingBox(handle) {267    return this._sessionForHandle(handle)._getBoundingBox(handle);268  }269  async scrollRectIntoViewIfNeeded(handle, rect) {270    return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);271  }272  async setScreencastOptions(options) {273    if (options) {274      await this._mainFrameSession._startScreencast(this, {275        format: 'jpeg',276        quality: options.quality,277        maxWidth: options.width,278        maxHeight: options.height279      });280    } else {281      await this._mainFrameSession._stopScreencast(this);282    }283  }284  rafCountForStablePosition() {285    return 1;286  }287  async getContentQuads(handle) {288    return this._sessionForHandle(handle)._getContentQuads(handle);289  }290  async setInputFiles(handle, files) {291    await handle.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), files);292  }293  async setInputFilePaths(handle, files) {294    const frame = await handle.ownerFrame();295    if (!frame) throw new Error('Cannot set input files to detached input element');296    const parentSession = this._sessionForFrame(frame);297    await parentSession._client.send('DOM.setFileInputFiles', {298      objectId: handle._objectId,299      files300    });301  }302  async adoptElementHandle(handle, to) {303    return this._sessionForHandle(handle)._adoptElementHandle(handle, to);304  }305  async getAccessibilityTree(needle) {306    return (0, _crAccessibility.getAccessibilityTree)(this._mainFrameSession._client, needle);307  }308  async inputActionEpilogue() {309    await this._mainFrameSession._client.send('Page.enable').catch(e => {});310  }311  async pdf(options) {312    return this._pdf.generate(options);313  }314  coverage() {315    return this._coverage;316  }317  async getFrameElement(frame) {318    let parent = frame.parentFrame();319    if (!parent) throw new Error('Frame has been detached.');320    const parentSession = this._sessionForFrame(parent);321    const {322      backendNodeId323    } = await parentSession._client.send('DOM.getFrameOwner', {324      frameId: frame._id325    }).catch(e => {326      if (e instanceof Error && e.message.includes('Frame with the given id was not found.')) (0, _stackTrace.rewriteErrorMessage)(e, 'Frame has been detached.');327      throw e;328    });329    parent = frame.parentFrame();330    if (!parent) throw new Error('Frame has been detached.');331    return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());332  }333}334exports.CRPage = CRPage;335class FrameSession {336  // Marks the oopif session that remote -> local transition has happened in the parent.337  // See Target.detachedFromTarget handler for details.338  constructor(crPage, client, targetId, parentSession) {339    this._client = void 0;340    this._crPage = void 0;341    this._page = void 0;342    this._networkManager = void 0;343    this._contextIdToContext = new Map();344    this._eventListeners = [];345    this._targetId = void 0;346    this._firstNonInitialNavigationCommittedPromise = void 0;347    this._firstNonInitialNavigationCommittedFulfill = () => {};348    this._firstNonInitialNavigationCommittedReject = e => {};349    this._windowId = void 0;350    this._swappedIn = false;351    this._videoRecorder = null;352    this._screencastId = null;353    this._screencastClients = new Set();354    this._evaluateOnNewDocumentIdentifiers = [];355    this._exposedBindingNames = [];356    this._client = client;357    this._crPage = crPage;358    this._page = crPage._page;359    this._targetId = targetId;360    this._networkManager = new _crNetworkManager.CRNetworkManager(client, this._page, parentSession ? parentSession._networkManager : null);361    this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {362      this._firstNonInitialNavigationCommittedFulfill = f;363      this._firstNonInitialNavigationCommittedReject = r;364    });365    client.once(_crConnection.CRSessionEvents.Disconnected, () => {366      this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));367    });368  }369  _isMainFrame() {370    return this._targetId === this._crPage._targetId;371  }372  _addRendererListeners() {373    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))]);374  }375  _addBrowserListeners() {376    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))]);377  }378  async _initialize(hasUIWindow) {379    const isSettingStorageState = this._page._browserContext.isSettingStorageState();380    if (!isSettingStorageState && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {381      const {382        windowId383      } = await this._client.send('Browser.getWindowForTarget');384      this._windowId = windowId;385    }386    let screencastOptions;387    if (!isSettingStorageState && this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) {388      const screencastId = (0, _utils.createGuid)();389      const outputFile = _path.default.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + '.webm');390      screencastOptions = { // validateBrowserContextOptions ensures correct video size.391        ...this._crPage._browserContext._options.recordVideo.size,392        outputFile393      };394      await this._crPage._browserContext._ensureVideosPath(); // Note: it is important to start video recorder before sending Page.startScreencast,395      // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.396      await this._createVideoRecorder(screencastId, screencastOptions);397      this._crPage.pageOrError().then(p => {398        if (p instanceof Error) this._stopVideoRecording().catch(() => {});399      });400    }401    let lifecycleEventsEnabled;402    if (!this._isMainFrame()) this._addRendererListeners();403    this._addBrowserListeners();404    const promises = [this._client.send('Page.enable'), this._client.send('Page.getFrameTree').then(({405      frameTree406    }) => {407      if (this._isMainFrame()) {408        this._handleFrameTree(frameTree);409        this._addRendererListeners();410      }411      const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)];412      for (const frame of localFrames) {413        // Note: frames might be removed before we send these.414        this._client._sendMayFail('Page.createIsolatedWorld', {415          frameId: frame._id,416          grantUniveralAccess: true,417          worldName: UTILITY_WORLD_NAME418        });419        for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source, false, undefined).catch(e => {});420        for (const source of this._crPage._browserContext.initScripts) frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});421      }422      const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';423      if (isInitialEmptyPage) {424        // Ignore lifecycle events for the initial empty page. It is never the final page425        // hence we are going to get more lifecycle updates after the actual navigation has426        // started (even if the target url is about:blank).427        lifecycleEventsEnabled.catch(e => {}).then(() => {428          this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));429        });430      } else {431        this._firstNonInitialNavigationCommittedFulfill();432        this._eventListeners.push(_eventsHelper.eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));433      }434    }), this._client.send('Log.enable', {}), lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', {435      enabled: true436    }), this._client.send('Runtime.enable', {}), this._client.send('Page.addScriptToEvaluateOnNewDocument', {437      source: '',438      worldName: UTILITY_WORLD_NAME439    }), this._networkManager.initialize(), this._client.send('Target.setAutoAttach', {440      autoAttach: true,441      waitForDebuggerOnStart: true,442      flatten: true443    })];444    if (!isSettingStorageState) {445      if (this._isMainFrame()) promises.push(this._client.send('Emulation.setFocusEmulationEnabled', {446        enabled: true447      }));448      const options = this._crPage._browserContext._options;449      if (options.bypassCSP) promises.push(this._client.send('Page.setBypassCSP', {450        enabled: true451      }));452      if (options.ignoreHTTPSErrors) promises.push(this._client.send('Security.setIgnoreCertificateErrors', {453        ignore: true454      }));455      if (this._isMainFrame()) promises.push(this._updateViewport());456      if (options.hasTouch) promises.push(this._client.send('Emulation.setTouchEmulationEnabled', {457        enabled: true458      }));459      if (options.javaScriptEnabled === false) promises.push(this._client.send('Emulation.setScriptExecutionDisabled', {460        value: true461      }));462      if (options.userAgent || options.locale) promises.push(this._client.send('Emulation.setUserAgentOverride', {463        userAgent: options.userAgent || '',464        acceptLanguage: options.locale465      }));466      if (options.locale) promises.push(emulateLocale(this._client, options.locale));467      if (options.timezoneId) promises.push(emulateTimezone(this._client, options.timezoneId));468      if (!this._crPage._browserContext._browser.options.headful) promises.push(this._setDefaultFontFamilies(this._client));469      promises.push(this._updateGeolocation(true));470      promises.push(this._updateExtraHTTPHeaders(true));471      promises.push(this._updateRequestInterception());472      promises.push(this._updateOffline(true));473      promises.push(this._updateHttpCredentials(true));474      promises.push(this._updateEmulateMedia(true));475      for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));476      for (const source of this._crPage._browserContext.initScripts) promises.push(this._evaluateOnNewDocument(source, 'main'));477      for (const source of this._crPage._page.initScripts) promises.push(this._evaluateOnNewDocument(source, 'main'));478      if (screencastOptions) promises.push(this._startVideoRecording(screencastOptions));479    }480    promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));481    promises.push(this._firstNonInitialNavigationCommittedPromise);482    await Promise.all(promises);483  }484  dispose() {485    _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);486    this._networkManager.dispose();487    this._crPage._sessions.delete(this._targetId);488  }489  async _navigate(frame, url, referrer) {490    const response = await this._client.send('Page.navigate', {491      url,492      referrer,493      frameId: frame._id494    });495    if (response.errorText) throw new Error(`${response.errorText} at ${url}`);496    return {497      newDocumentId: response.loaderId498    };499  }500  _onLifecycleEvent(event) {501    if (this._eventBelongsToStaleFrame(event.frameId)) return;502    if (event.name === 'load') this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');else if (event.name === 'DOMContentLoaded') this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');503  }504  _onFrameStoppedLoading(frameId) {505    if (this._eventBelongsToStaleFrame(frameId)) return;506    this._page._frameManager.frameStoppedLoading(frameId);507  }508  _handleFrameTree(frameTree) {509    this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);510    this._onFrameNavigated(frameTree.frame, true);511    if (!frameTree.childFrames) return;512    for (const child of frameTree.childFrames) this._handleFrameTree(child);513  }514  _eventBelongsToStaleFrame(frameId) {515    const frame = this._page._frameManager.frame(frameId); // Subtree may be already gone because some ancestor navigation destroyed the oopif.516    if (!frame) return true; // When frame goes remote, parent process may still send some events517    // related to the local frame before it sends frameDetached.518    // In this case, we already have a new session for this frame, so events519    // in the old session should be ignored.520    const session = this._crPage._sessionForFrame(frame);521    return session && session !== this && !session._swappedIn;522  }523  _onFrameAttached(frameId, parentFrameId) {524    const frameSession = this._crPage._sessions.get(frameId);525    if (frameSession && frameId !== this._targetId) {526      // This is a remote -> local frame transition.527      frameSession._swappedIn = true;528      const frame = this._page._frameManager.frame(frameId); // Frame or even a whole subtree may be already gone, because some ancestor did navigate.529      if (frame) this._page._frameManager.removeChildFramesRecursively(frame);530      return;531    }532    if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {533      // Parent frame may be gone already because some ancestor frame navigated and534      // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.535      // Be careful to not confuse this with "main frame navigated cross-process" scenario536      // where parentFrameId is null.537      return;538    }539    this._page._frameManager.frameAttached(frameId, parentFrameId);540  }541  _onFrameNavigated(framePayload, initial) {542    if (this._eventBelongsToStaleFrame(framePayload.id)) return;543    this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);544    if (!initial) this._firstNonInitialNavigationCommittedFulfill();545  }546  _onFrameRequestedNavigation(payload) {547    if (this._eventBelongsToStaleFrame(payload.frameId)) return;548    if (payload.disposition === 'currentTab') this._page._frameManager.frameRequestedNavigation(payload.frameId);549  }550  _onFrameNavigatedWithinDocument(frameId, url) {551    if (this._eventBelongsToStaleFrame(frameId)) return;552    this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);553  }554  _onFrameDetached(frameId, reason) {555    if (this._crPage._sessions.has(frameId)) {556      // This is a local -> remote frame transtion, where557      // Page.frameDetached arrives after Target.attachedToTarget.558      // We've already handled the new target and frame reattach - nothing to do here.559      return;560    }561    if (reason === 'swap') {562      // This is a local -> remote frame transtion, where563      // Page.frameDetached arrives before Target.attachedToTarget.564      // We should keep the frame in the tree, and it will be used for the new target.565      const frame = this._page._frameManager.frame(frameId);566      if (frame) this._page._frameManager.removeChildFramesRecursively(frame);567      return;568    } // Just a regular frame detach.569    this._page._frameManager.frameDetached(frameId);570  }571  _onExecutionContextCreated(contextPayload) {572    const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;573    if (!frame || this._eventBelongsToStaleFrame(frame._id)) return;574    const delegate = new _crExecutionContext.CRExecutionContext(this._client, contextPayload);575    let worldName = null;576    if (contextPayload.auxData && !!contextPayload.auxData.isDefault) worldName = 'main';else if (contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';577    const context = new dom.FrameExecutionContext(delegate, frame, worldName);578    context[contextDelegateSymbol] = delegate;579    if (worldName) frame._contextCreated(worldName, context);580    this._contextIdToContext.set(contextPayload.id, context);581  }582  _onExecutionContextDestroyed(executionContextId) {583    const context = this._contextIdToContext.get(executionContextId);584    if (!context) return;585    this._contextIdToContext.delete(executionContextId);586    context.frame._contextDestroyed(context);587  }588  _onExecutionContextsCleared() {589    for (const contextId of Array.from(this._contextIdToContext.keys())) this._onExecutionContextDestroyed(contextId);590  }591  _onAttachedToTarget(event) {592    const session = _crConnection.CRConnection.fromSession(this._client).session(event.sessionId);593    if (event.targetInfo.type === 'iframe') {594      // Frame id equals target id.595      const targetId = event.targetInfo.targetId;596      const frame = this._page._frameManager.frame(targetId);597      if (!frame) return; // Subtree may be already gone due to renderer/browser race.598      this._page._frameManager.removeChildFramesRecursively(frame);599      const frameSession = new FrameSession(this._crPage, session, targetId, this);600      this._crPage._sessions.set(targetId, frameSession);601      frameSession._initialize(false).catch(e => e);602      return;603    }604    if (event.targetInfo.type !== 'worker') {605      // Ideally, detaching should resume any target, but there is a bug in the backend.606      session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {607        this._client._sendMayFail('Target.detachFromTarget', {608          sessionId: event.sessionId609        });610      });611      return;612    }613    const url = event.targetInfo.url;614    const worker = new _page.Worker(this._page, url);615    this._page._addWorker(event.sessionId, worker);616    session.once('Runtime.executionContextCreated', async event => {617      worker._createExecutionContext(new _crExecutionContext.CRExecutionContext(session, event.context));618    }); // This might fail if the target is closed before we initialize.619    session._sendMayFail('Runtime.enable');620    session._sendMayFail('Network.enable');621    session._sendMayFail('Runtime.runIfWaitingForDebugger');622    session.on('Runtime.consoleAPICalled', event => {623      const args = event.args.map(o => worker._existingExecutionContext.createHandle(o));624      this._page._addConsoleMessage(event.type, args, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));625    });626    session.on('Runtime.exceptionThrown', exception => this._page.emit(_page.Page.Events.PageError, (0, _crProtocolHelper.exceptionToError)(exception.exceptionDetails))); // TODO: attribute workers to the right frame.627    this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId));628  }629  _onDetachedFromTarget(event) {630    // This might be a worker...631    this._page._removeWorker(event.sessionId); // ... or an oopif.632    const childFrameSession = this._crPage._sessions.get(event.targetId);633    if (!childFrameSession) return; // Usually, we get frameAttached in this session first and mark child as swappedIn.634    if (childFrameSession._swappedIn) {635      childFrameSession.dispose();636      return;637    } // However, sometimes we get detachedFromTarget before frameAttached.638    // In this case we don't know wheter this is a remote frame detach,639    // or just a remote -> local transition. In the latter case, frameAttached640    // is already inflight, so let's make a safe roundtrip to ensure it arrives.641    this._client.send('Page.enable').catch(e => null).then(() => {642      // Child was not swapped in - that means frameAttached did not happen and643      // this is remote detach rather than remote -> local swap.644      if (!childFrameSession._swappedIn) this._page._frameManager.frameDetached(event.targetId);645      childFrameSession.dispose();646    });647  }648  _onWindowOpen(event) {649    this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);650  }651  async _onConsoleAPI(event) {652    if (event.executionContextId === 0) {653      // DevTools protocol stores the last 1000 console messages. These654      // messages are always reported even for removed execution contexts. In655      // this case, they are marked with executionContextId = 0 and are656      // reported upon enabling Runtime agent.657      //658      // Ignore these messages since:659      // - there's no execution context we can use to operate with message660      //   arguments661      // - these messages are reported before Playwright clients can subscribe662      //   to the 'console'663      //   page event.664      //665      // @see https://github.com/GoogleChrome/puppeteer/issues/3865666      return;667    }668    const context = this._contextIdToContext.get(event.executionContextId);669    if (!context) return;670    const values = event.args.map(arg => context.createHandle(arg));671    this._page._addConsoleMessage(event.type, values, (0, _crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));672  }673  async _initBinding(binding) {674    const [, response] = await Promise.all([this._client.send('Runtime.addBinding', {675      name: binding.name676    }), this._client.send('Page.addScriptToEvaluateOnNewDocument', {677      source: binding.source678    })]);679    this._exposedBindingNames.push(binding.name);680    this._evaluateOnNewDocumentIdentifiers.push(response.identifier);681  }682  async _removeExposedBindings() {683    const names = this._exposedBindingNames;684    this._exposedBindingNames = [];685    await Promise.all(names.map(name => this._client.send('Runtime.removeBinding', {686      name687    })));688  }689  async _onBindingCalled(event) {690    const pageOrError = await this._crPage.pageOrError();691    if (!(pageOrError instanceof Error)) {692      const context = this._contextIdToContext.get(event.executionContextId);693      if (context) await this._page._onBindingCalled(event.payload, context);694    }695  }696  _onDialog(event) {...page.js
Source:page.js  
...287      needsHandle: options.handle288    });289    this._bindings.set(name, callback);290  }291  async _removeExposedBindings() {292    this._bindings.clear();293    await this._channel.removeExposedBindings();294  }295  async setExtraHTTPHeaders(headers) {296    (0, _network.validateHeaders)(headers);297    await this._channel.setExtraHTTPHeaders({298      headers: (0, _utils.headersObjectToArray)(headers)299    });300  }301  url() {302    return this._mainFrame.url();303  }304  async content() {305    return this._mainFrame.content();306  }307  async setContent(html, options) {308    return this._mainFrame.setContent(html, options);309  }310  async goto(url, options) {311    return this._mainFrame.goto(url, options);312  }313  async reload(options = {}) {314    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);315    return _network.Response.fromNullable((await this._channel.reload({ ...options,316      waitUntil317    })).response);318  }319  async waitForLoadState(state, options) {320    return this._mainFrame.waitForLoadState(state, options);321  }322  async waitForNavigation(options) {323    return this._mainFrame.waitForNavigation(options);324  }325  async waitForURL(url, options) {326    return this._mainFrame.waitForURL(url, options);327  }328  async waitForRequest(urlOrPredicate, options = {}) {329    const predicate = request => {330      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);331      return urlOrPredicate(request);332    };333    const trimmedUrl = trimUrl(urlOrPredicate);334    const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : undefined;335    return this._waitForEvent(_events.Events.Page.Request, {336      predicate,337      timeout: options.timeout338    }, logLine);339  }340  async waitForResponse(urlOrPredicate, options = {}) {341    const predicate = response => {342      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);343      return urlOrPredicate(response);344    };345    const trimmedUrl = trimUrl(urlOrPredicate);346    const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : undefined;347    return this._waitForEvent(_events.Events.Page.Response, {348      predicate,349      timeout: options.timeout350    }, logLine);351  }352  async waitForEvent(event, optionsOrPredicate = {}) {353    return this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);354  }355  async _waitForEvent(event, optionsOrPredicate, logLine) {356    return this._wrapApiCall(async () => {357      const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);358      const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;359      const waiter = _waiter.Waiter.createForEvent(this, event);360      if (logLine) waiter.log(logLine);361      waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);362      if (event !== _events.Events.Page.Crash) waiter.rejectOnEvent(this, _events.Events.Page.Crash, new Error('Page crashed'));363      if (event !== _events.Events.Page.Close) waiter.rejectOnEvent(this, _events.Events.Page.Close, new Error('Page closed'));364      const result = await waiter.waitForEvent(this, event, predicate);365      waiter.dispose();366      return result;367    });368  }369  async goBack(options = {}) {370    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);371    return _network.Response.fromNullable((await this._channel.goBack({ ...options,372      waitUntil373    })).response);374  }375  async goForward(options = {}) {376    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);377    return _network.Response.fromNullable((await this._channel.goForward({ ...options,378      waitUntil379    })).response);380  }381  async emulateMedia(options = {}) {382    await this._channel.emulateMedia({383      media: options.media === null ? 'null' : options.media,384      colorScheme: options.colorScheme === null ? 'null' : options.colorScheme,385      reducedMotion: options.reducedMotion === null ? 'null' : options.reducedMotion,386      forcedColors: options.forcedColors === null ? 'null' : options.forcedColors387    });388  }389  async setViewportSize(viewportSize) {390    this._viewportSize = viewportSize;391    await this._channel.setViewportSize({392      viewportSize393    });394  }395  viewportSize() {396    return this._viewportSize;397  }398  async evaluate(pageFunction, arg) {399    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);400    return this._mainFrame.evaluate(pageFunction, arg);401  }402  async addInitScript(script, arg) {403    const source = await (0, _clientHelper.evaluationScript)(script, arg);404    await this._channel.addInitScript({405      source406    });407  }408  async _removeInitScripts() {409    await this._channel.removeInitScripts();410  }411  async route(url, handler, options = {}) {412    this._routes.unshift(new _network.RouteHandler(this._browserContext._options.baseURL, url, handler, options.times));413    if (this._routes.length === 1) await this._channel.setNetworkInterceptionEnabled({414      enabled: true415    });416  }417  async unroute(url, handler) {418    this._routes = this._routes.filter(route => route.url !== url || handler && route.handler !== handler);419    if (!this._routes.length) await this._disableInterception();420  }421  async _unrouteAll() {422    this._routes = [];423    await this._disableInterception();424  }425  async _disableInterception() {426    await this._channel.setNetworkInterceptionEnabled({427      enabled: false428    });429  }430  async screenshot(options = {}) {431    const copy = { ...options,432      mask: undefined433    };434    if (!copy.type) copy.type = (0, _elementHandle.determineScreenshotType)(options);435    if (options.mask) {436      copy.mask = options.mask.map(locator => ({437        frame: locator._frame._channel,438        selector: locator._selector439      }));440    }441    copy.fonts = options._fonts;442    const result = await this._channel.screenshot(copy);443    const buffer = _buffer.Buffer.from(result.binary, 'base64');444    if (options.path) {445      await (0, _fileUtils.mkdirIfNeeded)(options.path);446      await _fs.default.promises.writeFile(options.path, buffer);447    }448    return buffer;449  }450  async _expectScreenshot(customStackTrace, options) {451    return this._wrapApiCall(async () => {452      var _options$screenshotOp, _options$screenshotOp2;453      const mask = (_options$screenshotOp = options.screenshotOptions) !== null && _options$screenshotOp !== void 0 && _options$screenshotOp.mask ? (_options$screenshotOp2 = options.screenshotOptions) === null || _options$screenshotOp2 === void 0 ? void 0 : _options$screenshotOp2.mask.map(locator => ({454        frame: locator._frame._channel,455        selector: locator._selector456      })) : undefined;457      const locator = options.locator ? {458        frame: options.locator._frame._channel,459        selector: options.locator._selector460      } : undefined;461      const expected = options.expected ? options.expected.toString('base64') : undefined;462      const result = await this._channel.expectScreenshot({ ...options,463        isNot: !!options.isNot,464        expected,465        locator,466        screenshotOptions: { ...options.screenshotOptions,467          mask468        }469      });470      return {471        log: result.log,472        actual: result.actual ? _buffer.Buffer.from(result.actual, 'base64') : undefined,473        previous: result.previous ? _buffer.Buffer.from(result.previous, 'base64') : undefined,474        diff: result.diff ? _buffer.Buffer.from(result.diff, 'base64') : undefined,475        errorMessage: result.errorMessage476      };477    }, false478    /* isInternal */479    , customStackTrace);480  }481  async title() {482    return this._mainFrame.title();483  }484  async bringToFront() {485    await this._channel.bringToFront();486  }487  async close(options = {488    runBeforeUnload: undefined489  }) {490    try {491      if (this._ownedContext) await this._ownedContext.close();else await this._channel.close(options);492    } catch (e) {493      if ((0, _errors.isSafeCloseError)(e)) return;494      throw e;495    }496  }497  isClosed() {498    return this._closed;499  }500  async click(selector, options) {501    return this._mainFrame.click(selector, options);502  }503  async dragAndDrop(source, target, options) {504    return this._mainFrame.dragAndDrop(source, target, options);505  }506  async dblclick(selector, options) {507    return this._mainFrame.dblclick(selector, options);508  }509  async tap(selector, options) {510    return this._mainFrame.tap(selector, options);511  }512  async fill(selector, value, options) {513    return this._mainFrame.fill(selector, value, options);514  }515  locator(selector, options) {516    return this.mainFrame().locator(selector, options);517  }518  frameLocator(selector) {519    return this.mainFrame().frameLocator(selector);520  }521  async focus(selector, options) {522    return this._mainFrame.focus(selector, options);523  }524  async textContent(selector, options) {525    return this._mainFrame.textContent(selector, options);526  }527  async innerText(selector, options) {528    return this._mainFrame.innerText(selector, options);529  }530  async innerHTML(selector, options) {531    return this._mainFrame.innerHTML(selector, options);532  }533  async getAttribute(selector, name, options) {534    return this._mainFrame.getAttribute(selector, name, options);535  }536  async inputValue(selector, options) {537    return this._mainFrame.inputValue(selector, options);538  }539  async isChecked(selector, options) {540    return this._mainFrame.isChecked(selector, options);541  }542  async isDisabled(selector, options) {543    return this._mainFrame.isDisabled(selector, options);544  }545  async isEditable(selector, options) {546    return this._mainFrame.isEditable(selector, options);547  }548  async isEnabled(selector, options) {549    return this._mainFrame.isEnabled(selector, options);550  }551  async isHidden(selector, options) {552    return this._mainFrame.isHidden(selector, options);553  }554  async isVisible(selector, options) {555    return this._mainFrame.isVisible(selector, options);556  }557  async hover(selector, options) {558    return this._mainFrame.hover(selector, options);559  }560  async selectOption(selector, values, options) {561    return this._mainFrame.selectOption(selector, values, options);562  }563  async setInputFiles(selector, files, options) {564    return this._mainFrame.setInputFiles(selector, files, options);565  }566  async type(selector, text, options) {567    return this._mainFrame.type(selector, text, options);568  }569  async press(selector, key, options) {570    return this._mainFrame.press(selector, key, options);571  }572  async check(selector, options) {573    return this._mainFrame.check(selector, options);574  }575  async uncheck(selector, options) {576    return this._mainFrame.uncheck(selector, options);577  }578  async setChecked(selector, checked, options) {579    return this._mainFrame.setChecked(selector, checked, options);580  }581  async waitForTimeout(timeout) {582    return this._mainFrame.waitForTimeout(timeout);583  }584  async waitForFunction(pageFunction, arg, options) {585    return this._mainFrame.waitForFunction(pageFunction, arg, options);586  }587  workers() {588    return [...this._workers];589  }590  on(event, listener) {591    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({592      intercepted: true593    });594    super.on(event, listener);595    return this;596  }597  addListener(event, listener) {598    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({599      intercepted: true600    });601    super.addListener(event, listener);602    return this;603  }604  off(event, listener) {605    super.off(event, listener);606    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({607      intercepted: false608    });609    return this;610  }611  removeListener(event, listener) {612    super.removeListener(event, listener);613    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({614      intercepted: false615    });616    return this;617  }618  async pause() {619    if (!require('inspector').url()) await this.context()._channel.pause();620  }621  async pdf(options = {}) {622    const transportOptions = { ...options623    };624    if (transportOptions.margin) transportOptions.margin = { ...transportOptions.margin625    };626    if (typeof options.width === 'number') transportOptions.width = options.width + 'px';627    if (typeof options.height === 'number') transportOptions.height = options.height + 'px';628    for (const margin of ['top', 'right', 'bottom', 'left']) {629      const index = margin;630      if (options.margin && typeof options.margin[index] === 'number') transportOptions.margin[index] = transportOptions.margin[index] + 'px';631    }632    const result = await this._channel.pdf(transportOptions);633    const buffer = _buffer.Buffer.from(result.pdf, 'base64');634    if (options.path) {635      await _fs.default.promises.mkdir(_path.default.dirname(options.path), {636        recursive: true637      });638      await _fs.default.promises.writeFile(options.path, buffer);639    }640    return buffer;641  }642  async _resetForReuse() {643    await this._unrouteAll();644    await this._removeInitScripts();645    await this._removeExposedBindings();646  }647}648exports.Page = Page;649class BindingCall extends _channelOwner.ChannelOwner {650  static from(channel) {651    return channel._object;652  }653  constructor(parent, type, guid, initializer) {654    super(parent, type, guid, initializer);655  }656  async call(func) {657    try {658      const frame = _frame.Frame.from(this._initializer.frame);659      const source = {...browserContext.js
Source:browserContext.js  
...256      needsHandle: options.handle257    });258    this._bindings.set(name, callback);259  }260  async _removeExposedBindings() {261    this._bindings.clear();262    await this._channel.removeExposedBindings();263  }264  async exposeFunction(name, callback) {265    await this._channel.exposeBinding({266      name267    });268    const binding = (source, ...args) => callback(...args);269    this._bindings.set(name, binding);270  }271  async route(url, handler, options = {}) {272    this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times));273    if (this._routes.length === 1) await this._channel.setNetworkInterceptionEnabled({274      enabled: true275    });276  }277  async unroute(url, handler) {278    this._routes = this._routes.filter(route => route.url !== url || handler && route.handler !== handler);279    if (!this._routes.length) await this._disableInterception();280  }281  async _unrouteAll() {282    this._routes = [];283    await this._disableInterception();284  }285  async _disableInterception() {286    await this._channel.setNetworkInterceptionEnabled({287      enabled: false288    });289  }290  async waitForEvent(event, optionsOrPredicate = {}) {291    return this._wrapApiCall(async () => {292      const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);293      const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;294      const waiter = _waiter.Waiter.createForEvent(this, event);295      waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);296      if (event !== _events.Events.BrowserContext.Close) waiter.rejectOnEvent(this, _events.Events.BrowserContext.Close, new Error('Context closed'));297      const result = await waiter.waitForEvent(this, event, predicate);298      waiter.dispose();299      return result;300    });301  }302  async storageState(options = {}) {303    const state = await this._channel.storageState();304    if (options.path) {305      await (0, _fileUtils.mkdirIfNeeded)(options.path);306      await _fs.default.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');307    }308    return state;309  }310  backgroundPages() {311    return [...this._backgroundPages];312  }313  serviceWorkers() {314    return [...this._serviceWorkers];315  }316  async newCDPSession(page) {317    // channelOwner.ts's validation messages don't handle the pseudo-union type, so we're explicit here318    if (!(page instanceof _page.Page) && !(page instanceof _frame.Frame)) throw new Error('page: expected Page or Frame');319    const result = await this._channel.newCDPSession(page instanceof _page.Page ? {320      page: page._channel321    } : {322      frame: page._channel323    });324    return _cdpSession.CDPSession.from(result.session);325  }326  _onClose() {327    var _this$_browserType, _this$_browserType$_c;328    if (this._browser) this._browser._contexts.delete(this);329    (_this$_browserType = this._browserType) === null || _this$_browserType === void 0 ? void 0 : (_this$_browserType$_c = _this$_browserType._contexts) === null || _this$_browserType$_c === void 0 ? void 0 : _this$_browserType$_c.delete(this);330    this.emit(_events.Events.BrowserContext.Close, this);331  }332  async close() {333    try {334      await this._wrapApiCall(async () => {335        var _this$_browserType2, _this$_browserType2$_;336        await ((_this$_browserType2 = this._browserType) === null || _this$_browserType2 === void 0 ? void 0 : (_this$_browserType2$_ = _this$_browserType2._onWillCloseContext) === null || _this$_browserType2$_ === void 0 ? void 0 : _this$_browserType2$_.call(_this$_browserType2, this));337        if (this._options.recordHar) {338          const har = await this._channel.harExport();339          const artifact = _artifact.Artifact.from(har.artifact);340          await artifact.saveAs(this._options.recordHar.path);341          await artifact.delete();342        }343      }, true);344      await this._channel.close();345      await this._closedPromise;346    } catch (e) {347      if ((0, _errors.isSafeCloseError)(e)) return;348      throw e;349    }350  }351  async _enableRecorder(params) {352    await this._channel.recorderSupplementEnable(params);353  }354  async _resetForReuse() {355    await this._unrouteAll();356    await this._removeInitScripts();357    await this._removeExposedBindings();358  }359}360exports.BrowserContext = BrowserContext;361async function prepareStorageState(options) {362  if (typeof options.storageState !== 'string') return options.storageState;363  try {364    return JSON.parse(await _fs.default.promises.readFile(options.storageState, 'utf8'));365  } catch (e) {366    (0, _stackTrace.rewriteErrorMessage)(e, `Error reading storage state from ${options.storageState}:\n` + e.message);367    throw e;368  }369}370async function prepareBrowserContextParams(options) {371  if (options.videoSize && !options.videosPath) throw new Error(`"videoSize" option requires "videosPath" to be specified`);...Using AI Code Generation
1const { chromium } = require('playwright');2const { _removeExposedBindings } = require('playwright/lib/server/browserContext');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.exposeBinding('foo', () => {});8  await page.exposeBinding('bar', () => {});9  await _removeExposedBindings(page);10  await page.evaluate(() => {11    console.log(window['foo']);12    console.log(window['bar']);13  });14  await browser.close();15})();16const { chromium } = require('playwright');17const { _removeExposedBindings } = require('playwright/lib/server/browserContext');18(async () => {19  const browser = await chromium.launch();20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.exposeBinding('foo', () => {});23  await page.exposeBinding('bar', () => {});24  await _removeExposedBindings(page);25  await browser.close();26})();27const { chromium } = require('playwright');28const { _removeExposedBindings } = require('playwright/lib/server/browserContext');29(async () => {30  const browser = await chromium.launch();31  const context = await browser.newContext();32  const page = await context.newPage();33  const page2 = await context.newPage();34  await page.exposeBinding('foo', () => {});35  await page.exposeBinding('bar', () => {});36  await page2.exposeBinding('foo', () => {});37  await page2.exposeBinding('bar', () => {});38  await _removeExposedBindings(page);39  await _removeExposedBindings(page2);40  await browser.close();41})();Using AI Code Generation
1const { chromium } = require('playwright');2const { _removeExposedBindings } = require('playwright/lib/server/chromium/crBrowser');3(async () => {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  await page.exposeFunction('foo', () => 'foo');7  await _removeExposedBindings(page);8  await page.evaluate(() => window.foo());9  await browser.close();10})();Using AI Code Generation
1const { _removeExposedBindings } = require('playwright/lib/server/chromium/crBrowser.js');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  _removeExposedBindings(page);7  await page.exposeBinding('foo', () => {});8  await browser.close();9})();10    at Object.throwProtocolError (/Users/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crConnection.js:263:15)11    at CRSession.dispatch (/Users/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crConnection.js:241:20)12    at CRConnection.dispatch (/Users/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crConnection.js:123:37)13    at CRSession.onMessage (/Users/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crConnection.js:276:20)14    at WebSocketTransport._ws.addEventListener (/Users/username/Downloads/playwright-test/node_modules/playwright/lib/server/chromium/crConnection.js:81:35)15    at WebSocket.onMessage (/Users/username/Downloads/playwright-test/node_modules/ws/lib/event-target.js:132:16)16    at WebSocket.emit (events.js:315:20)17    at Receiver.receiverOnMessage (/Users/username/Downloads/playwright-test/node_modules/ws/lib/websocket.js:800:20)18    at Receiver.emit (events.js:315:20)19    at Receiver.dataMessage (/Users/username/Downloads/playwright-test/node_modules/ws/lib/receiver.js:437:14)Using AI Code Generation
1const { Playwright } = require('playwright');2const { chromium } = require('playwright-chromium');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.fill('input[name="q"]', 'playwright');8  await page.click('input[name="btnK"]');9  await page.waitForSelector('text="Playwright - Google Search"');10  await page.screenshot({ path: `example.png` });11  await browser.close();12})();13const { Playwright } = require('playwright');14const { chromium } = require('playwright-chromium');15(async () => {16  const browser = await chromium.launch();17  const context = await browser.newContext();18  const page = await context.newPage();19  await page.fill('input[name="q"]', 'playwright');20  await page.click('input[name="btnK"]');21  await page.waitForSelector('text="Playwright - Google Search"');22  await page.screenshot({ path: `example.png` });23  await browser.close();24})();25const { Playwright } = require('playwright');26const { chromium } = require('playwright-chromium');27(async () => {28  const browser = await chromium.launch();29  const context = await browser.newContext();30  const page = await context.newPage();31  await page.fill('input[name="q"]', 'playwright');32  await page.click('input[name="btnK"]');33  await page.waitForSelector('text="Playwright - Google Search"');34  await page.screenshot({ path: `example.png` });35  await browser.close();36})();37const { Playwright } = require('playwright');38const { chromium } = require('playwright-chromium');39(async () => {40  const browser = await chromium.launch();41  const context = await browser.newContext();42  const page = await context.newPage();43  await page.fill('input[name="q"]', 'playwright');Using AI Code Generation
1const { Playwright } = require('playwright');2const { chromium } = require('playwright-chromium');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.fill('input[name="q"]', 'playwright');8  await page.click('input[name="btnK"]');9  await page.waitForSelector('text="Playwright - Google Search"');10  await page.screenshot({ path: `example.png` });11  await browser.close();12})();evaluate(() => {13    window.test();14  });15  await browser.close();16})();Using AI Code Generation
1const { chromium } = require'playwright');2async (3constbrowser= aait chromum.lauch();4  const page = await browser.newPage();5  await page.exposeBining('log', (surce, ...args) => {6    console.log('log:', ...args);7  });8  aait pageevalua(aync () => {9const { Playwright } = require('playwright');10const { chromium } = require('playwright-chromium');11(async () => {12  const browser = await chromium.launch();13  const context = await browser.newContext();14  const page = await context.newPage();15  await page.fill('input[name="q"]', 'playwright');16  await page.click('input[name="btnK"]');17  await page.waitForSelector('text="Playwright - Google Search"');18  await page.screenshot({ path: `example.png` });19  await browser.close();20})();21const { Playwright } = require('playwright');22const { chromium } = require('playwright-chromium');23(async () => {24  const browser = await chromium.launch();25  const context = await browser.newContext();26  const page = await context.newPage();27  await page.fill('input[name="q"]', 'playwright');28  await page.click('input[name="btnK"]');29  await page.waitForSelector('text="Playwright - Google Search"');30  await page.screenshot({ path: `example.png` });31  await browser.close();32})();33const { Playwright } = require('playwright');34const { chromium } = require('playwright-chromium');35(async () => {36  const browser = await chromium.launch();37  const context = await browser.newContext();38  const page = await context.newPage();39  await page.fill('input[name="q"]', 'playwright');Using AI Code Generation
1  const browser = await chromium.launch({ headless: false });2  const context = await browser.newContext();3  const page = await context.newPage();4  await page.exposeBinding('test', () => {});5  await page.evaluate(() => {6    window.test();7  });8  await _removeExposedBindings(page);9  await page.evaluate(() => {10    window.test();11  });12  await browser.close();13})();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.exposeBinding('log', (source, ...args) => {6    console.log('log:', ...args);7  });8  await page.evaluate(async () => {9    await window['log']('hello', 'world');10  });11  await browser.close();12})();Using AI Code Generation
1const { _removeExposedBindings } = require('playwright/lib/server/chromium/crBrowser');2_removeExposedBindings.call(page, ['pageFunction']);3const { _exposeBinding } = require('playwright/lib/server/chromium/crBrowser');4_exposeBinding.call(page, 'pageFunction', false, (source, ...args) => {5});6const { _onBindingCalled } = require('playwright/lib/server/chromium/crPage');7_onBindingCalled.call(page, {name: 'pageFunction', seq: 0, args: ['arg1', 'arg2']});8const { _evaluateExpression } = require('playwright/lib/server/chromium/crExecutionContext');9_evaluateExpression.call(page.mainFrame().executionContext(), '1 + 1', 'main');10const { _pageBindings } = require('playwright/lib/server/chromium/crExecutionContext');11_pageBindings.call(page.mainFrame().executionContext());12const { _contextCreated } = require('playwright/lib/server/chromium/crPage');13_contextCreated.call(page, {frameId: 'frameId', name: 'frameName', auxData: {isDefault: true}});14const { _contextDestroyed } = require('playwright/lib/server/chromium/crPage');15_contextDestroyed.call(page, {frameId: 'frameId'});16const { _onExecutionContextCreated } = require('playwright/lib/server/chromium/crPage');17_onExecutionContextCreated.call(page, {frameId: 'frameId', name: 'frameName', auxData: {isDefault: true}});18const { _onExecutionContextDestroyed } = require('playwright/lib/server/chromium/crPage');19_onExecutionContextDestroyed.call(page, {frameId: 'frameId'});20const { _onConsoleAPI }Using AI Code Generation
1const { _removeExposedBindings } = require('playwright/lib/server/frames');2await _removeExposedBindings(page);3await page.exposeBinding('name', false, () => {});4await page.exposeBinding('name', false, () => {5});6await page.exposeBinding('name', false, () => {7}, {8  handle: (source, ...args) => {9  }10});11await page.exposeBinding('name', false, () => {12}, {13  handle: (source, ...args) => {14  }15});16await page.exposeBinding('name', false, () => {17}, {18  handle: (source, ...args) => {19  }20});21await page.exposeBinding('name', false, () => {22}, {23  handle: (source, ...args) => {24  }25});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!!
