Best JavaScript code snippet using playwright-internal
crPage.js
Source:crPage.js  
...159  async exposeBinding(binding) {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  
...190    const binding = new PageBinding(name, playwrightBinding, needsHandle);191    this._pageBindings.set(name, binding);192    await this._delegate.exposeBinding(binding);193  }194  async removeExposedBindings() {195    this._pageBindings.clear();196    await this._delegate.removeExposedBindings();197  }198  setExtraHTTPHeaders(headers) {199    this._state.extraHTTPHeaders = headers;200    return this._delegate.updateExtraHTTPHeaders();201  }202  async _onBindingCalled(payload, context) {203    if (this._disconnected || this._closedState === 'closed') return;204    await PageBinding.dispatch(this, payload, context);205  }206  _addConsoleMessage(type, args, location, text) {207    const message = new _console.ConsoleMessage(this, type, text, args, location);208    const intercepted = this._frameManager.interceptConsoleMessage(message);209    if (intercepted || !this.listenerCount(Page.Events.Console)) args.forEach(arg => arg.dispose());else this.emit(Page.Events.Console, message);210  }...ffPage.js
Source:ffPage.js  
...285      name: binding.name,286      script: binding.source287    });288  }289  async removeExposedBindings() {// TODO: implement me.290  }291  didClose() {292    this._session.dispose();293    _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);294    this._networkManager.dispose();295    this._page._didClose();296  }297  async navigateFrame(frame, url, referer) {298    const response = await this._session.send('Page.navigate', {299      url,300      referer,301      frameId: frame._id302    });303    return {...crBrowser.js
Source:crBrowser.js  
...403  async doExposeBinding(binding) {404    for (const page of this.pages()) await page._delegate.exposeBinding(binding);405  }406  async doRemoveExposedBindings() {407    for (const page of this.pages()) await page._delegate.removeExposedBindings();408  }409  async doUpdateRequestInterception() {410    for (const page of this.pages()) await page._delegate.updateRequestInterception();411  }412  async doClose() {413    (0, _utils.assert)(this._browserContextId); // Headful chrome cannot dispose browser context with opened 'beforeunload'414    // dialogs, so we should close all that are currently opened.415    // We also won't get new ones since `Target.disposeBrowserContext` does not trigger416    // beforeunload.417    const openedBeforeUnloadDialogs = [];418    for (const crPage of this._browser._crPages.values()) {419      if (crPage._browserContext !== this) continue;420      const dialogs = [...crPage._page._frameManager._openedDialogs].filter(dialog => dialog.type() === 'beforeunload');421      openedBeforeUnloadDialogs.push(...dialogs);...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`);...wkBrowser.js
Source:wkBrowser.js  
...272  async doExposeBinding(binding) {273    for (const page of this.pages()) await page._delegate.exposeBinding(binding);274  }275  async doRemoveExposedBindings() {276    for (const page of this.pages()) await page._delegate.removeExposedBindings();277  }278  async doUpdateRequestInterception() {279    for (const page of this.pages()) await page._delegate.updateRequestInterception();280  }281  onClosePersistent() {}282  async doClose() {283    (0, _utils.assert)(this._browserContextId);284    await this._browser._browserSession.send('Playwright.deleteContext', {285      browserContextId: this._browserContextId286    });287    this._browser._contexts.delete(this._browserContextId);288  }289  async cancelDownload(uuid) {290    await this._browser._browserSession.send('Playwright.cancelDownload', {...pageDispatcher.js
Source:pageDispatcher.js  
...109      });110      return binding.promise();111    });112  }113  async removeExposedBindings() {114    await this._page.removeExposedBindings();115  }116  async setExtraHTTPHeaders(params, metadata) {117    await this._page.setExtraHTTPHeaders(params.headers);118  }119  async reload(params, metadata) {120    return {121      response: (0, _dispatcher.lookupNullableDispatcher)(await this._page.reload(metadata, params))122    };123  }124  async goBack(params, metadata) {125    return {126      response: (0, _dispatcher.lookupNullableDispatcher)(await this._page.goBack(metadata, params))127    };128  }...browserContextDispatcher.js
Source:browserContextDispatcher.js  
...131      });132      return binding.promise();133    });134  }135  async removeExposedBindings() {136    await this._context.removeExposedBindings();137  }138  async newPage(params, metadata) {139    return {140      page: (0, _dispatcher.lookupDispatcher)(await this._context.newPage(metadata))141    };142  }143  async cookies(params) {144    return {145      cookies: await this._context.cookies(params.urls)146    };147  }148  async addCookies(params) {149    await this._context.addCookies(params.cookies);150  }...Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext();5### 3.2.2. `exposeBinding(name, bindingFunction)`6- #`3.2.2. `expeseBinding(name,<bindingFunc[isn)`7Themhod adda uncton caldo`name`oun expo`window` objest ef iveryndiage in ehoryypage in the context()Whe> called, {funcion xecute `bindingFuncion` in nodeand returns a [Promse] which resovs to the return value of  bindingFunction . If the cbi aingFunction` rwturnsaa [Promise], ii will bt awaicedoext.exposeBinding('foo', (source, ...args) => {8   js return 7 * 8;9  }f Playwright Internal API10const { chromium } = require('playwright');11(async () => {12  const browser = await chromium.launch();13  const context = await browser.newContext();14  #a3.2.3.t clcarCtrkiis()`;15  await browser.close();16### 3.2.4. `addCookies(cookies)`17})();18###/3.2.4./`addCookies( Pokiet)`19Addskio=th=s ntxt.sAll pag)  wth isocc=tixtowiseehaventhtookessted. Cookiescn bobtaedvi[browsrC.cookies([urls])]20  context._options.exposedBindingSources = [];21  const page = await context.newPage();Using AI Code Generation
1  await browseremovrE.closde();s2})();3  awai page.valuae(() => {4    windowremovEdwindw);5   window.removeExposedBinding'dcment');6   windowremoveExposedBinding('navigto';7});8##await page.s*ree1.hot({ path: 'go gIe.png' });9  await browsnrsctase();10})l);11const { chrmium } = requreplaywright12(async () => {13  const browser =awaitchromium.launch(14```brwser.newPage();15```removeExpsedBindinwindw);16## *ndre.rtmtv ERun tdhe test(' ocumint');17    winow.r`movEdng('avir');18  });19awit.creeshot({pth:'oogl.pg'});20  awai browserclose();21})();node test.jsUsing AI Code Generation
1_options.dSourcs = [];2  nst age = awai contxt.newPage();3  wait bower.close(;4})();5;7(async () => {8  const browser = await chromium.launch();9  const context = await browser.newContext();10  await context.exposeBinding('foo', () => {});11  await context.removeBinding('foo');12  await browser.close();13})();14const { chromium } = require('playwright');15(async () => {16  const browser = await chromium.launch();17  const context = await browser.newContext();18  await context.exposeFunction('compute', (a, b) => a * b);19  const page = await context.newPage();20  const result = await page.evaluate(async (a, b) => {21    return await window.compute(a, b);22  }, 9, 4);23  await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27  const browser = await chromium.launch();28  const context = await browser.newContext();29  await context.exposeBinding('log', (source, ...args) => {30    console.log(`${source}: ${args.join(', ')}`);31  });32  const page = await context.newPage();33  await page.evaluate(() => {34    window.log('hello', 5, { foo: 'bar' });35  });36  await browser.close();37})();38const { chromium } = require('playwright');39(async () => {40  const browser = await chromium.launch();41  const context = await browser.newContext();42  await context.exposeBindingHandle('compute', (source, ...args) => {43    return source.page.evaluate(([a, b]) => a * b, args);Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext();5  await context.exposeBindingHandle('compute', (source, ...args) => {6const { removeExposedBinding } = require('playwright lib/server/browserContext');7removeExposedBinding.call(context, 'exposedBinding');8const { exposeBinding } = require('playwright/lib/server browserContext');9exposeBinding.call(context, 'exposedBinding', true, (source, ...args) => {10});Using AI Code Generation
1const playwright = require('playwright');2const { removeExposedBindings } = require('playwright/lib/server/browserContext');3(async () => {4    const browser = await playwright['chromium'].launch();5    const context = await browser.newContext();6    removeExposedBindings(context);7    const page = await context.newPage();8    await page.exposeFunction('window', () => {});9    await page.evaluate(() => {10        window.alert('hi');11    });12    await browser.close();13})();Using AI Code Generation
1const playwright = require('playwright');2const { removeExposedBindings } = require('playwright/lib/server/browserContext');3(async () => {4    const browser = await playwright['chromium'].launch();5    const context = await browser.newContext();6    removeExposedBindings(context);7    const page = await context.newPage();8    await page.exposeFunction('window', () => {});9    await page.evaluate(() => {10        window.alert('hi');11    });12    await browser.close();13})();  return source.page.evaluate(([a, b]) => a * b, args);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._client.send('Runtime.removeBinding', { name: 'window' });6  console.log(await page.evaluate(() => window));7  await browser.close();8})(Using AI Code Generation
1const playwright = require('playwright');2const { removeExposedBindings } = require('playwright/lib/server/browserContext');3(async () => {4    const browser = await playwright['chromium'].launch();5    const context = await browser.newContext();6    removeExposedBindings(context);7    const page = await context.newPage();8    await page.exposeFunction('window', () => {});9    await page.evaluate(() => {10        window.alert('hi');11    });12    await browser.close();13})();code to use removeExposedBindings method of Playwright Internal API14const { chromium } = require('playwright');15(async () => {16  const browser = await chromium.launch();17  const page = await browser.newPage();18  await page.context().removeBindings('window');19  await page.context().removeBindings('console');20  await page.context().removeBindings('alert');21  await page.context().removeBindings('prompt');22  await page.context().removeBindings('confirm');23  await page.context().removeBindings('beforeunload');24  await browser.close();25})();26#### browserContext.removeBindings(name)27#### page.removeBindings(name)28- [Remove Bindings](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!!
