Best JavaScript code snippet using playwright-internal
page.js
Source:page.js  
1"use strict";2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports.Page = exports.BindingCall = void 0;6var _events = require("./events");7var _utils = require("../utils/utils");8var _timeoutSettings = require("../utils/timeoutSettings");9var _serializers = require("../protocol/serializers");10var _accessibility = require("./accessibility");11var _channelOwner = require("./channelOwner");12var _consoleMessage = require("./consoleMessage");13var _dialog = require("./dialog");14var _download = require("./download");15var _elementHandle = require("./elementHandle");16var _worker = require("./worker");17var _frame = require("./frame");18var _input = require("./input");19var _jsHandle = require("./jsHandle");20var _network = require("./network");21var _fileChooser = require("./fileChooser");22var _buffer = require("buffer");23var _coverage = require("./coverage");24var _waiter = require("./waiter");25var _fs = _interopRequireDefault(require("fs"));26var _path = _interopRequireDefault(require("path"));27var _clientHelper = require("./clientHelper");28var _errors = require("../utils/errors");29var _video = require("./video");30var _artifact = require("./artifact");31function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }32/**33 * Copyright 2017 Google Inc. All rights reserved.34 * Modifications copyright (c) Microsoft Corporation.35 *36 * Licensed under the Apache License, Version 2.0 (the "License");37 * you may not use this file except in compliance with the License.38 * You may obtain a copy of the License at39 *40 *     http://www.apache.org/licenses/LICENSE-2.041 *42 * Unless required by applicable law or agreed to in writing, software43 * distributed under the License is distributed on an "AS IS" BASIS,44 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.45 * See the License for the specific language governing permissions and46 * limitations under the License.47 */48class Page extends _channelOwner.ChannelOwner {49  static from(page) {50    return page._object;51  }52  static fromNullable(page) {53    return page ? Page.from(page) : null;54  }55  constructor(parent, type, guid, initializer) {56    super(parent, type, guid, initializer);57    this._browserContext = void 0;58    this._ownedContext = void 0;59    this._mainFrame = void 0;60    this._frames = new Set();61    this._workers = new Set();62    this._closed = false;63    this._closedOrCrashedPromise = void 0;64    this._viewportSize = void 0;65    this._routes = [];66    this.accessibility = void 0;67    this.coverage = void 0;68    this.keyboard = void 0;69    this.mouse = void 0;70    this.request = void 0;71    this.touchscreen = void 0;72    this._bindings = new Map();73    this._timeoutSettings = void 0;74    this._video = null;75    this._opener = void 0;76    this._browserContext = parent;77    this._timeoutSettings = new _timeoutSettings.TimeoutSettings(this._browserContext._timeoutSettings);78    this.accessibility = new _accessibility.Accessibility(this._channel);79    this.keyboard = new _input.Keyboard(this);80    this.mouse = new _input.Mouse(this);81    this.request = this._browserContext.request;82    this.touchscreen = new _input.Touchscreen(this);83    this._mainFrame = _frame.Frame.from(initializer.mainFrame);84    this._mainFrame._page = this;85    this._frames.add(this._mainFrame);86    this._viewportSize = initializer.viewportSize || null;87    this._closed = initializer.isClosed;88    this._opener = Page.fromNullable(initializer.opener);89    this._channel.on('bindingCall', ({90      binding91    }) => this._onBinding(BindingCall.from(binding)));92    this._channel.on('close', () => this._onClose());93    this._channel.on('console', ({94      message95    }) => this.emit(_events.Events.Page.Console, _consoleMessage.ConsoleMessage.from(message)));96    this._channel.on('crash', () => this._onCrash());97    this._channel.on('dialog', ({98      dialog99    }) => {100      const dialogObj = _dialog.Dialog.from(dialog);101      if (!this.emit(_events.Events.Page.Dialog, dialogObj)) {102        if (dialogObj.type() === 'beforeunload') dialog.accept({}).catch(() => {});else dialog.dismiss().catch(() => {});103      }104    });105    this._channel.on('domcontentloaded', () => this.emit(_events.Events.Page.DOMContentLoaded, this));106    this._channel.on('download', ({107      url,108      suggestedFilename,109      artifact110    }) => {111      const artifactObject = _artifact.Artifact.from(artifact);112      this.emit(_events.Events.Page.Download, new _download.Download(this, url, suggestedFilename, artifactObject));113    });114    this._channel.on('fileChooser', ({115      element,116      isMultiple117    }) => this.emit(_events.Events.Page.FileChooser, new _fileChooser.FileChooser(this, _elementHandle.ElementHandle.from(element), isMultiple)));118    this._channel.on('frameAttached', ({119      frame120    }) => this._onFrameAttached(_frame.Frame.from(frame)));121    this._channel.on('frameDetached', ({122      frame123    }) => this._onFrameDetached(_frame.Frame.from(frame)));124    this._channel.on('load', () => this.emit(_events.Events.Page.Load, this));125    this._channel.on('pageError', ({126      error127    }) => this.emit(_events.Events.Page.PageError, (0, _serializers.parseError)(error)));128    this._channel.on('route', ({129      route,130      request131    }) => this._onRoute(_network.Route.from(route), _network.Request.from(request)));132    this._channel.on('video', ({133      artifact134    }) => {135      const artifactObject = _artifact.Artifact.from(artifact);136      this._forceVideo()._artifactReady(artifactObject);137    });138    this._channel.on('webSocket', ({139      webSocket140    }) => this.emit(_events.Events.Page.WebSocket, _network.WebSocket.from(webSocket)));141    this._channel.on('worker', ({142      worker143    }) => this._onWorker(_worker.Worker.from(worker)));144    this.coverage = new _coverage.Coverage(this._channel);145    this._closedOrCrashedPromise = Promise.race([new Promise(f => this.once(_events.Events.Page.Close, f)), new Promise(f => this.once(_events.Events.Page.Crash, f))]);146  }147  _onFrameAttached(frame) {148    frame._page = this;149    this._frames.add(frame);150    if (frame._parentFrame) frame._parentFrame._childFrames.add(frame);151    this.emit(_events.Events.Page.FrameAttached, frame);152  }153  _onFrameDetached(frame) {154    this._frames.delete(frame);155    frame._detached = true;156    if (frame._parentFrame) frame._parentFrame._childFrames.delete(frame);157    this.emit(_events.Events.Page.FrameDetached, frame);158  }159  _onRoute(route, request) {160    for (const routeHandler of this._routes) {161      if (routeHandler.matches(request.url())) {162        try {163          routeHandler.handle(route, request);164        } finally {165          if (!routeHandler.isActive()) {166            this._routes.splice(this._routes.indexOf(routeHandler), 1);167            if (!this._routes.length) this._wrapApiCall(() => this._disableInterception(), true).catch(() => {});168          }169        }170        return;171      }172    }173    this._browserContext._onRoute(route, request);174  }175  async _onBinding(bindingCall) {176    const func = this._bindings.get(bindingCall._initializer.name);177    if (func) {178      await bindingCall.call(func);179      return;180    }181    await this._browserContext._onBinding(bindingCall);182  }183  _onWorker(worker) {184    this._workers.add(worker);185    worker._page = this;186    this.emit(_events.Events.Page.Worker, worker);187  }188  _onClose() {189    this._closed = true;190    this._browserContext._pages.delete(this);191    this._browserContext._backgroundPages.delete(this);192    this.emit(_events.Events.Page.Close, this);193  }194  _onCrash() {195    this.emit(_events.Events.Page.Crash, this);196  }197  context() {198    return this._browserContext;199  }200  async opener() {201    if (!this._opener || this._opener.isClosed()) return null;202    return this._opener;203  }204  mainFrame() {205    return this._mainFrame;206  }207  frame(frameSelector) {208    const name = (0, _utils.isString)(frameSelector) ? frameSelector : frameSelector.name;209    const url = (0, _utils.isObject)(frameSelector) ? frameSelector.url : undefined;210    (0, _utils.assert)(name || url, 'Either name or url matcher should be specified');211    return this.frames().find(f => {212      if (name) return f.name() === name;213      return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, f.url(), url);214    }) || null;215  }216  frames() {217    return [...this._frames];218  }219  setDefaultNavigationTimeout(timeout) {220    this._timeoutSettings.setDefaultNavigationTimeout(timeout);221    this._wrapApiCall(async () => {222      this._channel.setDefaultNavigationTimeoutNoReply({223        timeout224      });225    }, true);226  }227  setDefaultTimeout(timeout) {228    this._timeoutSettings.setDefaultTimeout(timeout);229    this._wrapApiCall(async () => {230      this._channel.setDefaultTimeoutNoReply({231        timeout232      });233    }, true);234  }235  _forceVideo() {236    if (!this._video) this._video = new _video.Video(this, this._connection);237    return this._video;238  }239  video() {240    // Note: we are creating Video object lazily, because we do not know241    // BrowserContextOptions when constructing the page - it is assigned242    // too late during launchPersistentContext.243    if (!this._browserContext._options.recordVideo) return null;244    return this._forceVideo();245  }246  async $(selector, options) {247    return this._mainFrame.$(selector, options);248  }249  async waitForSelector(selector, options) {250    return this._mainFrame.waitForSelector(selector, options);251  }252  async dispatchEvent(selector, type, eventInit, options) {253    return this._mainFrame.dispatchEvent(selector, type, eventInit, options);254  }255  async evaluateHandle(pageFunction, arg) {256    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);257    return this._mainFrame.evaluateHandle(pageFunction, arg);258  }259  async $eval(selector, pageFunction, arg) {260    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);261    return this._mainFrame.$eval(selector, pageFunction, arg);262  }263  async $$eval(selector, pageFunction, arg) {264    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);265    return this._mainFrame.$$eval(selector, pageFunction, arg);266  }267  async $$(selector) {268    return this._mainFrame.$$(selector);269  }270  async addScriptTag(options = {}) {271    return this._mainFrame.addScriptTag(options);272  }273  async addStyleTag(options = {}) {274    return this._mainFrame.addStyleTag(options);275  }276  async exposeFunction(name, callback) {277    await this._channel.exposeBinding({278      name279    });280    const binding = (source, ...args) => callback(...args);281    this._bindings.set(name, binding);282  }283  async exposeBinding(name, callback, options = {}) {284    await this._channel.exposeBinding({285      name,286      needsHandle: options.handle287    });288    this._bindings.set(name, callback);289  }290  async setExtraHTTPHeaders(headers) {291    (0, _network.validateHeaders)(headers);292    await this._channel.setExtraHTTPHeaders({293      headers: (0, _utils.headersObjectToArray)(headers)294    });295  }296  url() {297    return this._mainFrame.url();298  }299  async content() {300    return this._mainFrame.content();301  }302  async setContent(html, options) {303    return this._mainFrame.setContent(html, options);304  }305  async goto(url, options) {306    return this._mainFrame.goto(url, options);307  }308  async reload(options = {}) {309    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);310    return _network.Response.fromNullable((await this._channel.reload({ ...options,311      waitUntil312    })).response);313  }314  async waitForLoadState(state, options) {315    return this._mainFrame.waitForLoadState(state, options);316  }317  async waitForNavigation(options) {318    return this._mainFrame.waitForNavigation(options);319  }320  async waitForURL(url, options) {321    return this._mainFrame.waitForURL(url, options);322  }323  async waitForRequest(urlOrPredicate, options = {}) {324    const predicate = request => {325      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);326      return urlOrPredicate(request);327    };328    const trimmedUrl = trimUrl(urlOrPredicate);329    const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : undefined;330    return this._waitForEvent(_events.Events.Page.Request, {331      predicate,332      timeout: options.timeout333    }, logLine);334  }335  async waitForResponse(urlOrPredicate, options = {}) {336    const predicate = response => {337      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);338      return urlOrPredicate(response);339    };340    const trimmedUrl = trimUrl(urlOrPredicate);341    const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : undefined;342    return this._waitForEvent(_events.Events.Page.Response, {343      predicate,344      timeout: options.timeout345    }, logLine);346  }347  async waitForEvent(event, optionsOrPredicate = {}) {348    return this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);349  }350  async _waitForEvent(event, optionsOrPredicate, logLine) {351    return this._wrapApiCall(async () => {352      const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);353      const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;354      const waiter = _waiter.Waiter.createForEvent(this, event);355      if (logLine) waiter.log(logLine);356      waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);357      if (event !== _events.Events.Page.Crash) waiter.rejectOnEvent(this, _events.Events.Page.Crash, new Error('Page crashed'));358      if (event !== _events.Events.Page.Close) waiter.rejectOnEvent(this, _events.Events.Page.Close, new Error('Page closed'));359      const result = await waiter.waitForEvent(this, event, predicate);360      waiter.dispose();361      return result;362    });363  }364  async goBack(options = {}) {365    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);366    return _network.Response.fromNullable((await this._channel.goBack({ ...options,367      waitUntil368    })).response);369  }370  async goForward(options = {}) {371    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);372    return _network.Response.fromNullable((await this._channel.goForward({ ...options,373      waitUntil374    })).response);375  }376  async emulateMedia(options = {}) {377    await this._channel.emulateMedia({378      media: options.media === null ? 'null' : options.media,379      colorScheme: options.colorScheme === null ? 'null' : options.colorScheme,380      reducedMotion: options.reducedMotion === null ? 'null' : options.reducedMotion,381      forcedColors: options.forcedColors === null ? 'null' : options.forcedColors382    });383  }384  async setViewportSize(viewportSize) {385    this._viewportSize = viewportSize;386    await this._channel.setViewportSize({387      viewportSize388    });389  }390  viewportSize() {391    return this._viewportSize;392  }393  async evaluate(pageFunction, arg) {394    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);395    return this._mainFrame.evaluate(pageFunction, arg);396  }397  async addInitScript(script, arg) {398    const source = await (0, _clientHelper.evaluationScript)(script, arg);399    await this._channel.addInitScript({400      source401    });402  }403  async route(url, handler, options = {}) {404    this._routes.unshift(new _network.RouteHandler(this._browserContext._options.baseURL, url, handler, options.times));405    if (this._routes.length === 1) await this._channel.setNetworkInterceptionEnabled({406      enabled: true407    });408  }409  async unroute(url, handler) {410    this._routes = this._routes.filter(route => route.url !== url || handler && route.handler !== handler);411    if (!this._routes.length) await this._disableInterception();412  }413  async _disableInterception() {414    await this._channel.setNetworkInterceptionEnabled({415      enabled: false416    });417  }418  async screenshot(options = {}) {419    const copy = { ...options420    };421    if (!copy.type) copy.type = (0, _elementHandle.determineScreenshotType)(options);422    const result = await this._channel.screenshot(copy);423    const buffer = _buffer.Buffer.from(result.binary, 'base64');424    if (options.path) {425      await (0, _utils.mkdirIfNeeded)(options.path);426      await _fs.default.promises.writeFile(options.path, buffer);427    }428    return buffer;429  }430  async title() {431    return this._mainFrame.title();432  }433  async bringToFront() {434    await this._channel.bringToFront();435  }436  async close(options = {437    runBeforeUnload: undefined438  }) {439    try {440      if (this._ownedContext) await this._ownedContext.close();else await this._channel.close(options);441    } catch (e) {442      if ((0, _errors.isSafeCloseError)(e)) return;443      throw e;444    }445  }446  isClosed() {447    return this._closed;448  }449  async click(selector, options) {450    return this._mainFrame.click(selector, options);451  }452  async dragAndDrop(source, target, options) {453    return this._mainFrame.dragAndDrop(source, target, options);454  }455  async dblclick(selector, options) {456    return this._mainFrame.dblclick(selector, options);457  }458  async tap(selector, options) {459    return this._mainFrame.tap(selector, options);460  }461  async fill(selector, value, options) {462    return this._mainFrame.fill(selector, value, options);463  }464  locator(selector, options) {465    return this.mainFrame().locator(selector, options);466  }467  frameLocator(selector) {468    return this.mainFrame().frameLocator(selector);469  }470  async focus(selector, options) {471    return this._mainFrame.focus(selector, options);472  }473  async textContent(selector, options) {474    return this._mainFrame.textContent(selector, options);475  }476  async innerText(selector, options) {477    return this._mainFrame.innerText(selector, options);478  }479  async innerHTML(selector, options) {480    return this._mainFrame.innerHTML(selector, options);481  }482  async getAttribute(selector, name, options) {483    return this._mainFrame.getAttribute(selector, name, options);484  }485  async inputValue(selector, options) {486    return this._mainFrame.inputValue(selector, options);487  }488  async isChecked(selector, options) {489    return this._mainFrame.isChecked(selector, options);490  }491  async isDisabled(selector, options) {492    return this._mainFrame.isDisabled(selector, options);493  }494  async isEditable(selector, options) {495    return this._mainFrame.isEditable(selector, options);496  }497  async isEnabled(selector, options) {498    return this._mainFrame.isEnabled(selector, options);499  }500  async isHidden(selector, options) {501    return this._mainFrame.isHidden(selector, options);502  }503  async isVisible(selector, options) {504    return this._mainFrame.isVisible(selector, options);505  }506  async hover(selector, options) {507    return this._mainFrame.hover(selector, options);508  }509  async selectOption(selector, values, options) {510    return this._mainFrame.selectOption(selector, values, options);511  }512  async setInputFiles(selector, files, options) {513    return this._mainFrame.setInputFiles(selector, files, options);514  }515  async type(selector, text, options) {516    return this._mainFrame.type(selector, text, options);517  }518  async press(selector, key, options) {519    return this._mainFrame.press(selector, key, options);520  }521  async check(selector, options) {522    return this._mainFrame.check(selector, options);523  }524  async uncheck(selector, options) {525    return this._mainFrame.uncheck(selector, options);526  }527  async setChecked(selector, checked, options) {528    return this._mainFrame.setChecked(selector, checked, options);529  }530  async waitForTimeout(timeout) {531    return this._mainFrame.waitForTimeout(timeout);532  }533  async waitForFunction(pageFunction, arg, options) {534    return this._mainFrame.waitForFunction(pageFunction, arg, options);535  }536  workers() {537    return [...this._workers];538  }539  on(event, listener) {540    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({541      intercepted: true542    });543    super.on(event, listener);544    return this;545  }546  addListener(event, listener) {547    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({548      intercepted: true549    });550    super.addListener(event, listener);551    return this;552  }553  off(event, listener) {554    super.off(event, listener);555    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({556      intercepted: false557    });558    return this;559  }560  removeListener(event, listener) {561    super.removeListener(event, listener);562    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({563      intercepted: false564    });565    return this;566  }567  async pause() {568    await this.context()._channel.pause();569  }570  async pdf(options = {}) {571    const transportOptions = { ...options572    };573    if (transportOptions.margin) transportOptions.margin = { ...transportOptions.margin574    };575    if (typeof options.width === 'number') transportOptions.width = options.width + 'px';576    if (typeof options.height === 'number') transportOptions.height = options.height + 'px';577    for (const margin of ['top', 'right', 'bottom', 'left']) {578      const index = margin;579      if (options.margin && typeof options.margin[index] === 'number') transportOptions.margin[index] = transportOptions.margin[index] + 'px';580    }581    const result = await this._channel.pdf(transportOptions);582    const buffer = _buffer.Buffer.from(result.pdf, 'base64');583    if (options.path) {584      await _fs.default.promises.mkdir(_path.default.dirname(options.path), {585        recursive: true586      });587      await _fs.default.promises.writeFile(options.path, buffer);588    }589    return buffer;590  }591}592exports.Page = Page;593class BindingCall extends _channelOwner.ChannelOwner {594  static from(channel) {595    return channel._object;596  }597  constructor(parent, type, guid, initializer) {598    super(parent, type, guid, initializer);599  }600  async call(func) {601    try {602      const frame = _frame.Frame.from(this._initializer.frame);603      const source = {604        context: frame._page.context(),605        page: frame._page,606        frame607      };608      let result;609      if (this._initializer.handle) result = await func(source, _jsHandle.JSHandle.from(this._initializer.handle));else result = await func(source, ...this._initializer.args.map(_jsHandle.parseResult));610      this._channel.resolve({611        result: (0, _jsHandle.serializeArgument)(result)612      }).catch(() => {});613    } catch (e) {614      this._channel.reject({615        error: (0, _serializers.serializeError)(e)616      }).catch(() => {});617    }618  }619}620exports.BindingCall = BindingCall;621function trimEnd(s) {622  if (s.length > 50) s = s.substring(0, 50) + '\u2026';623  return s;624}625function trimUrl(param) {626  if ((0, _utils.isRegExp)(param)) return `/${trimEnd(param.source)}/${param.flags}`;627  if ((0, _utils.isString)(param)) return `"${trimEnd(param)}"`;...frame.js
Source:frame.js  
...77    return this._page;78  }79  async goto(url, options = {}) {80    return this._wrapApiCall(async channel => {81      const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);82      return network.Response.fromNullable((await channel.goto({83        url,84        ...options,85        waitUntil86      })).response);87    });88  }89  _setupNavigationWaiter(channel, options) {90    const waiter = new _waiter.Waiter(channel, '');91    if (this._page.isClosed()) waiter.rejectImmediately(new Error('Navigation failed because page was closed!'));92    waiter.rejectOnEvent(this._page, _events2.Events.Page.Close, new Error('Navigation failed because page was closed!'));93    waiter.rejectOnEvent(this._page, _events2.Events.Page.Crash, new Error('Navigation failed because page crashed!'));94    waiter.rejectOnEvent(this._page, _events2.Events.Page.FrameDetached, new Error('Navigating frame was detached!'), frame => frame === this);95    const timeout = this._page._timeoutSettings.navigationTimeout(options);96    waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`);97    return waiter;98  }99  async waitForNavigation(options = {}) {100    return this._page._wrapApiCall(async channel => {101      const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);102      const waiter = this._setupNavigationWaiter(channel, options);103      const toUrl = typeof options.url === 'string' ? ` to "${options.url}"` : '';104      waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);105      const navigatedEvent = await waiter.waitForEvent(this._eventEmitter, 'navigated', event => {106        var _this$_page;107        // Any failed navigation results in a rejection.108        if (event.error) return true;109        waiter.log(`  navigated to "${event.url}"`);110        return (0, _clientHelper.urlMatches)((_this$_page = this._page) === null || _this$_page === void 0 ? void 0 : _this$_page.context()._options.baseURL, event.url, options.url);111      });112      if (navigatedEvent.error) {113        const e = new Error(navigatedEvent.error);114        e.stack = '';115        await waiter.waitForPromise(Promise.reject(e));116      }117      if (!this._loadStates.has(waitUntil)) {118        await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {119          waiter.log(`  "${s}" event fired`);120          return s === waitUntil;121        });122      }123      const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;124      const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;125      waiter.dispose();126      return response;127    });128  }129  async waitForLoadState(state = 'load', options = {}) {130    state = verifyLoadState('state', state);131    if (this._loadStates.has(state)) return;132    return this._page._wrapApiCall(async channel => {133      const waiter = this._setupNavigationWaiter(channel, options);134      await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {135        waiter.log(`  "${s}" event fired`);136        return s === state;137      });138      waiter.dispose();139    });140  }141  async waitForURL(url, options = {}) {142    var _this$_page2;143    if ((0, _clientHelper.urlMatches)((_this$_page2 = this._page) === null || _this$_page2 === void 0 ? void 0 : _this$_page2.context()._options.baseURL, this.url(), url)) return await this.waitForLoadState(options === null || options === void 0 ? void 0 : options.waitUntil, options);144    await this.waitForNavigation({145      url,146      ...options147    });148  }149  async frameElement() {150    return this._wrapApiCall(async channel => {151      return _elementHandle.ElementHandle.from((await channel.frameElement()).element);152    });153  }154  async evaluateHandle(pageFunction, arg) {155    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);156    return this._wrapApiCall(async channel => {157      const result = await channel.evaluateExpressionHandle({158        expression: String(pageFunction),159        isFunction: typeof pageFunction === 'function',160        arg: (0, _jsHandle.serializeArgument)(arg)161      });162      return _jsHandle.JSHandle.from(result.handle);163    });164  }165  async evaluate(pageFunction, arg) {166    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);167    return this._wrapApiCall(async channel => {168      const result = await channel.evaluateExpression({169        expression: String(pageFunction),170        isFunction: typeof pageFunction === 'function',171        arg: (0, _jsHandle.serializeArgument)(arg)172      });173      return (0, _jsHandle.parseResult)(result.value);174    });175  }176  async $(selector, options) {177    return this._wrapApiCall(async channel => {178      const result = await channel.querySelector({179        selector,180        ...options181      });182      return _elementHandle.ElementHandle.fromNullable(result.element);183    });184  }185  async waitForSelector(selector, options = {}) {186    return this._wrapApiCall(async channel => {187      if (options.visibility) throw new Error('options.visibility is not supported, did you mean options.state?');188      if (options.waitFor && options.waitFor !== 'visible') throw new Error('options.waitFor is not supported, did you mean options.state?');189      const result = await channel.waitForSelector({190        selector,191        ...options192      });193      return _elementHandle.ElementHandle.fromNullable(result.element);194    });195  }196  async dispatchEvent(selector, type, eventInit, options = {}) {197    return this._wrapApiCall(async channel => {198      await channel.dispatchEvent({199        selector,200        type,201        eventInit: (0, _jsHandle.serializeArgument)(eventInit),202        ...options203      });204    });205  }206  async $eval(selector, pageFunction, arg) {207    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);208    return this._wrapApiCall(async channel => {209      const result = await channel.evalOnSelector({210        selector,211        expression: String(pageFunction),212        isFunction: typeof pageFunction === 'function',213        arg: (0, _jsHandle.serializeArgument)(arg)214      });215      return (0, _jsHandle.parseResult)(result.value);216    });217  }218  async $$eval(selector, pageFunction, arg) {219    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);220    return this._wrapApiCall(async channel => {221      const result = await channel.evalOnSelectorAll({222        selector,223        expression: String(pageFunction),224        isFunction: typeof pageFunction === 'function',225        arg: (0, _jsHandle.serializeArgument)(arg)226      });227      return (0, _jsHandle.parseResult)(result.value);228    });229  }230  async $$(selector) {231    return this._wrapApiCall(async channel => {232      const result = await channel.querySelectorAll({233        selector234      });235      return result.elements.map(e => _elementHandle.ElementHandle.from(e));236    });237  }238  async content() {239    return this._wrapApiCall(async channel => {240      return (await channel.content()).value;241    });242  }243  async setContent(html, options = {}) {244    return this._wrapApiCall(async channel => {245      const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);246      await channel.setContent({247        html,248        ...options,249        waitUntil250      });251    });252  }253  name() {254    return this._name || '';255  }256  url() {257    return this._url;258  }259  parentFrame() {260    return this._parentFrame;261  }262  childFrames() {263    return Array.from(this._childFrames);264  }265  isDetached() {266    return this._detached;267  }268  async addScriptTag(options = {}) {269    return this._wrapApiCall(async channel => {270      const copy = { ...options271      };272      if (copy.path) {273        copy.content = (await _fs.default.promises.readFile(copy.path)).toString();274        copy.content += '//# sourceURL=' + copy.path.replace(/\n/g, '');275      }276      return _elementHandle.ElementHandle.from((await channel.addScriptTag({ ...copy277      })).element);278    });279  }280  async addStyleTag(options = {}) {281    return this._wrapApiCall(async channel => {282      const copy = { ...options283      };284      if (copy.path) {285        copy.content = (await _fs.default.promises.readFile(copy.path)).toString();286        copy.content += '/*# sourceURL=' + copy.path.replace(/\n/g, '') + '*/';287      }288      return _elementHandle.ElementHandle.from((await channel.addStyleTag({ ...copy289      })).element);290    });291  }292  async click(selector, options = {}) {293    return this._wrapApiCall(async channel => {294      return await channel.click({295        selector,296        ...options297      });298    });299  }300  async dblclick(selector, options = {}) {301    return this._wrapApiCall(async channel => {302      return await channel.dblclick({303        selector,304        ...options305      });306    });307  }308  async dragAndDrop(source, target, options = {}) {309    return this._wrapApiCall(async channel => {310      return await channel.dragAndDrop({311        source,312        target,313        ...options314      });315    });316  }317  async tap(selector, options = {}) {318    return this._wrapApiCall(async channel => {319      return await channel.tap({320        selector,321        ...options322      });323    });324  }325  async fill(selector, value, options = {}) {326    return this._wrapApiCall(async channel => {327      return await channel.fill({328        selector,329        value,330        ...options331      });332    });333  }334  locator(selector) {335    return new _locator.Locator(this, selector);336  }337  async focus(selector, options = {}) {338    return this._wrapApiCall(async channel => {339      await channel.focus({340        selector,341        ...options342      });343    });344  }345  async textContent(selector, options = {}) {346    return this._wrapApiCall(async channel => {347      const value = (await channel.textContent({348        selector,349        ...options350      })).value;351      return value === undefined ? null : value;352    });353  }354  async innerText(selector, options = {}) {355    return this._wrapApiCall(async channel => {356      return (await channel.innerText({357        selector,358        ...options359      })).value;360    });361  }362  async innerHTML(selector, options = {}) {363    return this._wrapApiCall(async channel => {364      return (await channel.innerHTML({365        selector,366        ...options367      })).value;368    });369  }370  async getAttribute(selector, name, options = {}) {371    return this._wrapApiCall(async channel => {372      const value = (await channel.getAttribute({373        selector,374        name,375        ...options376      })).value;377      return value === undefined ? null : value;378    });379  }380  async inputValue(selector, options = {}) {381    return this._wrapApiCall(async channel => {382      return (await channel.inputValue({383        selector,384        ...options385      })).value;386    });387  }388  async isChecked(selector, options = {}) {389    return this._wrapApiCall(async channel => {390      return (await channel.isChecked({391        selector,392        ...options393      })).value;394    });395  }396  async isDisabled(selector, options = {}) {397    return this._wrapApiCall(async channel => {398      return (await channel.isDisabled({399        selector,400        ...options401      })).value;402    });403  }404  async isEditable(selector, options = {}) {405    return this._wrapApiCall(async channel => {406      return (await channel.isEditable({407        selector,408        ...options409      })).value;410    });411  }412  async isEnabled(selector, options = {}) {413    return this._wrapApiCall(async channel => {414      return (await channel.isEnabled({415        selector,416        ...options417      })).value;418    });419  }420  async isHidden(selector, options = {}) {421    return this._wrapApiCall(async channel => {422      return (await channel.isHidden({423        selector,424        ...options425      })).value;426    });427  }428  async isVisible(selector, options = {}) {429    return this._wrapApiCall(async channel => {430      return (await channel.isVisible({431        selector,432        ...options433      })).value;434    });435  }436  async hover(selector, options = {}) {437    return this._wrapApiCall(async channel => {438      await channel.hover({439        selector,440        ...options441      });442    });443  }444  async selectOption(selector, values, options = {}) {445    return this._wrapApiCall(async channel => {446      return (await channel.selectOption({447        selector,448        ...(0, _elementHandle.convertSelectOptionValues)(values),449        ...options450      })).values;451    });452  }453  async setInputFiles(selector, files, options = {}) {454    return this._wrapApiCall(async channel => {455      await channel.setInputFiles({456        selector,457        files: await (0, _elementHandle.convertInputFiles)(files),458        ...options459      });460    });461  }462  async type(selector, text, options = {}) {463    return this._wrapApiCall(async channel => {464      await channel.type({465        selector,466        text,467        ...options468      });469    });470  }471  async press(selector, key, options = {}) {472    return this._wrapApiCall(async channel => {473      await channel.press({474        selector,475        key,476        ...options477      });478    });479  }480  async check(selector, options = {}) {481    return this._wrapApiCall(async channel => {482      await channel.check({483        selector,484        ...options485      });486    });487  }488  async uncheck(selector, options = {}) {489    return this._wrapApiCall(async channel => {490      await channel.uncheck({491        selector,492        ...options493      });494    });495  }496  async setChecked(selector, checked, options) {497    if (checked) await this.check(selector, options);else await this.uncheck(selector, options);498  }499  async waitForTimeout(timeout) {500    return this._wrapApiCall(async channel => {501      await channel.waitForTimeout({502        timeout503      });504    });505  }506  async waitForFunction(pageFunction, arg, options = {}) {507    return this._wrapApiCall(async channel => {508      if (typeof options.polling === 'string') (0, _utils.assert)(options.polling === 'raf', 'Unknown polling option: ' + options.polling);509      const result = await channel.waitForFunction({ ...options,510        pollingInterval: options.polling === 'raf' ? undefined : options.polling,511        expression: String(pageFunction),512        isFunction: typeof pageFunction === 'function',513        arg: (0, _jsHandle.serializeArgument)(arg)514      });515      return _jsHandle.JSHandle.from(result.handle);516    });517  }518  async title() {519    return this._wrapApiCall(async channel => {520      return (await channel.title()).value;521    });522  }523}524exports.Frame = Frame;525function verifyLoadState(name, waitUntil) {526  if (waitUntil === 'networkidle0') waitUntil = 'networkidle';527  if (!_types.kLifecycleEvents.has(waitUntil)) throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle)`);528  return waitUntil;...Using AI Code Generation
1(async () => {2  const { chromium } = require('playwright');3  const browser = await chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.waitForLoadState('load');7  const result = await page.evaluate(() => {8    return window.__playwright__internal__verifyLoadState('load');9  });10  console.log(result);11  await browser.close();12})();13await page.waitForLoadState('load');14await page.waitForLoadState('domcontentloaded');15await page.waitForLoadState('networkidle');16await page.waitForLoadState('load');17await page.waitForLoadState('domcontentloaded');18await page.waitForLoadState('networkidle');19await page.waitForLoadState('load');20await page.waitForLoadState('domcontentloaded');21await page.waitForLoadState('networkidle');22await page.waitForLoadState('load');23await page.waitForLoadState('domcontentloaded');Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch({headless: false});4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.waitForLoadState('networkidle');7  await browser.close();8})();Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright.chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.waitForLoadState('networkidle');7  await browser.close();8})();9Example 2: Using waitForLoadState() method to wait for the page to load10const playwright = require('playwright');11(async () => {12  const browser = await playwright.chromium.launch();13  const context = await browser.newContext();14  const page = await context.newPage();15  await page.waitForLoadState('domcontentloaded');16  await browser.close();17})();18Example 3: Using waitForLoadState() method to wait for the page to load19const playwright = require('playwright');20(async () => {21  const browser = await playwright.chromium.launch();22  const context = await browser.newContext();23  const page = await context.newPage();24  await page.waitForLoadState('load');25  await browser.close();26})();27Recommended Posts: Playwright | waitForLoadState() method28Playwright | waitForNavigation() method29Playwright | waitForRequest() method30Playwright | waitForResponse() method31Playwright | waitForSelector() method32Playwright | waitForTimeout() method33Playwright | waitForURL() method34Playwright | waitForEvent() method35Playwright | waitForFileChooser() method36Playwright | waitForFunction() method37Playwright | waitForRequest() method38Playwright | waitForResponse() method39Playwright | waitForSelector() method40Playwright | waitForTimeout() method41Playwright | waitForURL() method42Playwright | waitForEvent() method43Playwright | waitForFileChooser() method44Playwright | waitForFunction() method45Playwright | waitForNavigation() method46Playwright | verifyLoadState() method47Playwright | verifyRequest() method48Playwright | verifyResponse() method49Playwright | verifySelector() method50Playwright | verifyTimeout() method51Playwright | verifyURL() method52Playwright | verifyEvent() methodUsing AI Code Generation
1const { verifyLoadState } = require('playwright/lib/server/browserContext');2const { chromium } = require('playwright');3(async () => {4    const browser = await chromium.launch();5    const context = await browser.newContext();6    const page = await context.newPage();7    const loadState = await verifyLoadState(page);8    console.log(loadState);9    await browser.close();10})();Using AI Code Generation
1const { verifyLoadState } = require('playwright/lib/server/browserContext.js');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await verifyLoadState(page);8  await browser.close();9})();10    at verifyLoadState (/Users/username/playwright/test.js:6:11)11    at processTicksAndRejections (internal/process/task_queues.js:93:5)12    at async Object.<anonymous> (/Users/username/playwright/test.js:10:3)Using AI Code Generation
1const { verifyLoadState } = require('playwright/lib/server/browserContext');2const { chromium } = require('playwright');3const path = require('path');4(async () => {5  const browser = await chromium.launch({ headless: false });6  const context = await browser.newContext();7  const page = await context.newPage();8  await page.waitForLoadState('load');9  await page.screenshot({ path: path.join(__dirname, 'google.png') });10  await browser.close();11})();Using AI Code Generation
1const { verifyLoadState } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const { chromium } = require('playwright');3async function main() {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.click('text=Google apps');8  await page.click('text=YouTube');9  await page.click('text=Sign in');10  await page.fill('input[name="identifier"]', 'test');11  await page.click('text=Next');12  await page.fill('input[name="password"]', 'test');13  await page.click('text=Next');14  await page.click('text=Create');Using AI Code Generation
1const { verifyLoadState } = require('@playwright/test/lib/server/frames');2const frame = page.mainFrame();3await verifyLoadState(frame, 'networkidle');4const { verifyLoadState } = require('@playwright/test/lib/server/frames');5const frame = page.mainFrame();6await verifyLoadState(frame, 'load');7const { verifyLoadState } = require('@playwright/test/lib/server/frames');8const frame = page.mainFrame();9await verifyLoadState(frame, 'domcontentloaded');10const { verifyLoadState } = require('@playwright/test/lib/server/frames');11const frame = page.mainFrame();12await verifyLoadState(frame, 'networkidle');13const { verifyLoadState } = require('@playwright/test/lib/server/frames');14const frame = page.mainFrame();15await verifyLoadState(frame, 'load');16const { verifyLoadState } = require('@playwright/test/lib/server/frames');17const frame = page.mainFrame();18await verifyLoadState(frame, 'domcontentloaded');19const { verifyLoadState } = require('@playwright/test/lib/server/frames');20const frame = page.mainFrame();21await verifyLoadState(frame, 'networkidle');22const { verifyLoadState } = require('@playwright/test/lib/server/frames');23const frame = page.mainFrame();24await verifyLoadState(frame, 'load');25const { verifyLoadState } = require('@playwright/test/lib/server/frames');26const frame = page.mainFrame();27await verifyLoadState(frame, 'domcontentloaded');28const { verifyLoadState } = require('@playwright/test/lib/server/frames');29const frame = page.mainFrame();30await verifyLoadState(frame, 'networkidle');31const { verifyLoadState } = require('@playwright/test/lib/server/frames');Using AI Code Generation
1const { verifyLoadState } = require('playwright/lib/internal/loader');2(async () => {3  await verifyLoadState('page', 'Page');4  await verifyLoadState('browser', 'Browser');5  await verifyLoadState('browserContext', 'BrowserContext');6  await verifyLoadState('deviceDescriptors', 'deviceDescriptors');7  await verifyLoadState('android', 'android');8  await verifyLoadState('chromium', 'chromium');9  await verifyLoadState('firefox', 'firefox');10  await verifyLoadState('webkit', 'webkit');11  await verifyLoadState('electron', 'electron');12  await verifyLoadState('selectors', 'selectors');13  await verifyLoadState('traceViewer', 'traceViewer');14  await verifyLoadState('accessibility', 'accessibility');15  await verifyLoadState('download', 'download');16  await verifyLoadState('electron', 'electron');17  await verifyLoadState('tracing', 'tracing');18  await verifyLoadState('webkit', 'webkit');19  await verifyLoadState('chromium', 'chromium');20  await verifyLoadState('firefox', 'firefox');21  await verifyLoadState('android', 'android');22  await verifyLoadState('deviceDescriptors', 'deviceDescriptors');23  await verifyLoadState('electron', 'electron');24  await verifyLoadState('selectors', 'selectors');25  await verifyLoadState('traceViewer', 'traceViewer');26  await verifyLoadState('accessibility', 'accessibility');27  await verifyLoadState('download', 'download');28  await verifyLoadState('electron', 'electron');29  await verifyLoadState('tracing', 'tracing');30  await verifyLoadState('webkit', 'webkit');31  await verifyLoadState('chromium', 'chromium');32  await verifyLoadState('firefox', 'firefox');33  await verifyLoadState('android', 'android');34  await verifyLoadState('deviceDescriptors', 'deviceDescriptors');35  await verifyLoadState('electron', 'electron');36  await verifyLoadState('selectors', 'selectors');37  await verifyLoadState('traceViewer', 'traceViewer');38  await verifyLoadState('accessibility', 'accessibility');39  await verifyLoadState('download', 'download');40  await verifyLoadState('electron', 'electron');41  await verifyLoadState('tracing', 'tracing');42  await verifyLoadState('webkit', 'webkit');43  await verifyLoadState('Using AI Code Generation
1const { verifyLoadState } = require('playwright/lib/internal/loader');2verifyLoadState('playwright-firefox', '0.12.1', '0.12.1');3const { firefox } = require('playwright-firefox');4(async () => {5  const browser = await firefox.launch();6  const page = await browser.newPage();7  await page.screenshot({ path: 'google.png' });8  await browser.close();9})();10[Apache 2.0](/LICENSE)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!!
