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)}"`;...elementHandle.js
Source:elementHandle.js  
...160  }161  async screenshot(options = {}) {162    const copy = { ...options163    };164    if (!copy.type) copy.type = determineScreenshotType(options);165    const result = await this._elementChannel.screenshot(copy);166    const buffer = Buffer.from(result.binary, 'base64');167    if (options.path) {168      await (0, _utils.mkdirIfNeeded)(options.path);169      await _fs.default.promises.writeFile(options.path, buffer);170    }171    return buffer;172  }173  async $(selector) {174    return ElementHandle.fromNullable((await this._elementChannel.querySelector({175      selector176    })).element);177  }178  async $$(selector) {179    const result = await this._elementChannel.querySelectorAll({180      selector181    });182    return result.elements.map(h => ElementHandle.from(h));183  }184  async $eval(selector, pageFunction, arg) {185    const result = await this._elementChannel.evalOnSelector({186      selector,187      expression: String(pageFunction),188      isFunction: typeof pageFunction === 'function',189      arg: (0, _jsHandle.serializeArgument)(arg)190    });191    return (0, _jsHandle.parseResult)(result.value);192  }193  async $$eval(selector, pageFunction, arg) {194    const result = await this._elementChannel.evalOnSelectorAll({195      selector,196      expression: String(pageFunction),197      isFunction: typeof pageFunction === 'function',198      arg: (0, _jsHandle.serializeArgument)(arg)199    });200    return (0, _jsHandle.parseResult)(result.value);201  }202  async waitForElementState(state, options = {}) {203    return await this._elementChannel.waitForElementState({204      state,205      ...options206    });207  }208  async waitForSelector(selector, options = {}) {209    const result = await this._elementChannel.waitForSelector({210      selector,211      ...options212    });213    return ElementHandle.fromNullable(result.element);214  }215}216exports.ElementHandle = ElementHandle;217function convertSelectOptionValues(values) {218  if (values === null) return {};219  if (!Array.isArray(values)) values = [values];220  if (!values.length) return {};221  for (let i = 0; i < values.length; i++) (0, _utils.assert)(values[i] !== null, `options[${i}]: expected object, got null`);222  if (values[0] instanceof ElementHandle) return {223    elements: values.map(v => v._elementChannel)224  };225  if ((0, _utils.isString)(values[0])) return {226    options: values.map(value => ({227      value228    }))229  };230  return {231    options: values232  };233}234async function convertInputFiles(files) {235  const items = Array.isArray(files) ? files : [files];236  const filePayloads = await Promise.all(items.map(async item => {237    if (typeof item === 'string') {238      return {239        name: _path.default.basename(item),240        buffer: (await _fs.default.promises.readFile(item)).toString('base64')241      };242    } else {243      return {244        name: item.name,245        mimeType: item.mimeType,246        buffer: item.buffer.toString('base64')247      };248    }249  }));250  return filePayloads;251}252function determineScreenshotType(options) {253  if (options.path) {254    const mimeType = mime.getType(options.path);255    if (mimeType === 'image/png') return 'png';else if (mimeType === 'image/jpeg') return 'jpeg';256    throw new Error(`path: unsupported mime type "${mimeType}"`);257  }258  return options.type;...Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright.chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  const screenshotType = await page._delegate.determineScreenshotType({7  });8  console.log(screenshotType);9  await browser.close();10})();11{12}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.screenshot({ path: 'google.png' });7  await browser.close();8})();9const determineScreenshotType = require('playwright/lib/server/screenshotter').determineScreenshotType;10(async () => {11  const screenshotType = await determineScreenshotType('google.png');12  console.log('screenshot type is: ' + screenshotType);13})();Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright['chromium'].launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  const screenshotType = await page._delegate.determineScreenshotType({7  });8  console.log(screenshotType);9  await browser.close();10})();11{ output: 'png', omitBackground: true }12const playwright = require('playwright');13(async () => {14  const browser = await playwright['chromium'].launch();15  const context = await browser.newContext();16  const page = await context.newPage();17  const screenshotType = await page._delegate.screenshot({18  });19  console.log(screenshotType);20  await browser.close();21})();Using AI Code Generation
1const { determineScreenshotType } = require('playwright/lib/server/screenshotter');2const { takeScreenshot } = require('playwright/lib/server/screenshotter');3const fs = require('fs').promises;4const path = require('path');5(async () => {6  const screenshotType = determineScreenshotType({7  });8  const screenshotBuffer = await takeScreenshot({9    viewportSize: { width: 100, height: 100 },10    clip: { x: 0, y: 0, width: 100, height: 100 },11  });12  await fs.writeFile(path.join(__dirname, 'screenshot.png'), screenshotBuffer);13})();14module.exports = {15  use: {16  },17    {18      use: {19        viewport: { width: 1280, height: 720 },20      },21    },22};23import { PlaywrightTestConfig } from '@playwright/test';24const config: PlaywrightTestConfig = {25  use: {26  },27    {28      use: {29        viewport: { width: 1280, height: 720 },30      },31    },32};33export default config;34module.exports = {35  use: {36  },37    {Using AI Code Generation
1const { determineScreenshotType } = require('playwright/lib/server/screenshotter');2const screenshotType = determineScreenshotType({3  clip: {4  }5});6console.log(screenshotType);Using AI Code Generation
1const { determineScreenshotType } = require('playwright/lib/server/screenshotter');2const { createPNG } = require('playwright/lib/server/screenshot');3const fs = require('fs');4const path = require('path');5const imageBuffer = fs.readFileSync(path.join(__dirname, './image.png'));6const image = createPNG(imageBuffer);7const type = determineScreenshotType(image);8console.log(type);Using AI Code Generation
1const { determineScreenshotType } = require('playwright/lib/server/screenshotter');2const { PNG } = require('pngjs');3const fs = require('fs');4const file = fs.readFileSync('screenshot.png');5const png = PNG.sync.read(file);6const type = determineScreenshotType(png);7console.log(type);Using AI Code Generation
1const { determineScreenshotType } = require('playwright/lib/server/screenshotter');2const { createCanvas } = require('canvas');3const fs = require('fs');4(async () => {5  const canvas = createCanvas(100, 100);6  const context = canvas.getContext('2d');7  context.fillStyle = 'white';8  context.fillRect(0, 0, 100, 100);9  const screenshotType = await determineScreenshotType(canvas, 'jpeg');10  console.log(screenshotType);11  const buffer = canvas.toBuffer(screenshotType);12  fs.writeFileSync('test.jpeg', buffer);13})();14{15  "scripts": {16  },17  "dependencies": {18  }19}Using AI Code Generation
1const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');2const screenshotType = determineScreenshotType('image/png');3console.log(screenshotType);4const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');5const screenshotType = determineScreenshotType('image/jpg');6console.log(screenshotType);7const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');8const screenshotType = determineScreenshotType('image/jpeg');9console.log(screenshotType);10const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');11const screenshotType = determineScreenshotType('image/webp');12console.log(screenshotType);13const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');14const screenshotType = determineScreenshotType('image/gif');15console.log(screenshotType);16const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');17const screenshotType = determineScreenshotType('image/svg+xml');18console.log(screenshotType);19const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');20const screenshotType = determineScreenshotType('image/avif');21console.log(screenshotType);22const { determineScreenshotType } = require('@playwright/test/lib/server/screenshotter');23const screenshotType = determineScreenshotType('image/heic');24console.log(screenshotType);25const { determineScreenshotType } = requireUsing AI Code Generation
1const { determineScreenshotType } = require('playwright-core/lib/server/supplements/screenshotter/screenshotter');2const screenshotType = determineScreenshotType('image/png');3console.log(screenshotType);4import { determineScreenshotType } from 'playwright-core/lib/server/supplements/screenshotter/screenshotter';5const screenshotType = determineScreenshotType('image/png');6console.log(screenshotType);7> import { determineScreenshotType } from 'playwright-core/lib/server/supplements/screenshotter/screenshotter';8>     at ModuleJob._instantiate (internal/modules/esm/module_job.js:96:21)9>     at async ModuleJob.run (internal/modules/esm/module_job.js:135:5)10>     at async Loader.import (internal/modules/esm/loader.js:166:24)11>     at async Object.loadESM (internal/process/esm_loader.js:68:5)12I have also tried to use the following code to import the method but it is not working:13const { determineScreenshotType } = require('playwright-core/lib/server/supplements/screenshotter/screenshotter');14const screenshotType = determineScreenshotType('image/png');15console.log(screenshotType);16> const screenshotType = determineScreenshotType('image/png');17>     at ModuleJob.run (internal/modules/esm/module_job.js:152:23)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!!
