How to use _resetForReuse method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

browserContext.js

Source: browserContext.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.BrowserContext = void 0;
7exports.prepareBrowserContextParams = prepareBrowserContextParams;
8
9var _page = require("./page");
10
11var _frame = require("./frame");
12
13var network = _interopRequireWildcard(require("./network"));
14
15var _fs = _interopRequireDefault(require("fs"));
16
17var _channelOwner = require("./channelOwner");
18
19var _clientHelper = require("./clientHelper");
20
21var _browser = require("./browser");
22
23var _worker = require("./worker");
24
25var _events = require("./events");
26
27var _timeoutSettings = require("../common/timeoutSettings");
28
29var _waiter = require("./waiter");
30
31var _utils = require("../utils");
32
33var _fileUtils = require("../utils/fileUtils");
34
35var _errors = require("../common/errors");
36
37var _cdpSession = require("./cdpSession");
38
39var _tracing = require("./tracing");
40
41var _artifact = require("./artifact");
42
43var _fetch = require("./fetch");
44
45var _clientInstrumentation = require("./clientInstrumentation");
46
47var _stackTrace = require("../utils/stackTrace");
48
49function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
50
51function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
52
53function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
54
55/**
56 * Copyright 2017 Google Inc. All rights reserved.
57 * Modifications copyright (c) Microsoft Corporation.
58 *
59 * Licensed under the Apache License, Version 2.0 (the "License");
60 * you may not use this file except in compliance with the License.
61 * You may obtain a copy of the License at
62 *
63 *     http://www.apache.org/licenses/LICENSE-2.0
64 *
65 * Unless required by applicable law or agreed to in writing, software
66 * distributed under the License is distributed on an "AS IS" BASIS,
67 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
68 * See the License for the specific language governing permissions and
69 * limitations under the License.
70 */
71class BrowserContext extends _channelOwner.ChannelOwner {
72  static from(context) {
73    return context._object;
74  }
75
76  static fromNullable(context) {
77    return context ? BrowserContext.from(context) : null;
78  }
79
80  constructor(parent, type, guid, initializer) {
81    var _this$_browser;
82
83    super(parent, type, guid, initializer, (0, _clientInstrumentation.createInstrumentation)());
84    this._pages = new Set();
85    this._routes = [];
86    this._browser = null;
87    this._browserType = void 0;
88    this._bindings = new Map();
89    this._timeoutSettings = new _timeoutSettings.TimeoutSettings();
90    this._ownerPage = void 0;
91    this._closedPromise = void 0;
92    this._options = {};
93    this.request = void 0;
94    this.tracing = void 0;
95    this._backgroundPages = new Set();
96    this._serviceWorkers = new Set();
97    this._isChromium = void 0;
98    if (parent instanceof _browser.Browser) this._browser = parent;
99    this._isChromium = ((_this$_browser = this._browser) === null || _this$_browser === void 0 ? void 0 : _this$_browser._name) === 'chromium';
100    this.tracing = _tracing.Tracing.from(initializer.tracing);
101    this.request = _fetch.APIRequestContext.from(initializer.APIRequestContext);
102
103    this._channel.on('bindingCall', ({
104      binding
105    }) => this._onBinding(_page.BindingCall.from(binding)));
106
107    this._channel.on('close', () => this._onClose());
108
109    this._channel.on('page', ({
110      page
111    }) => this._onPage(_page.Page.from(page)));
112
113    this._channel.on('route', ({
114      route,
115      request
116    }) => this._onRoute(network.Route.from(route), network.Request.from(request)));
117
118    this._channel.on('backgroundPage', ({
119      page
120    }) => {
121      const backgroundPage = _page.Page.from(page);
122
123      this._backgroundPages.add(backgroundPage);
124
125      this.emit(_events.Events.BrowserContext.BackgroundPage, backgroundPage);
126    });
127
128    this._channel.on('serviceWorker', ({
129      worker
130    }) => {
131      const serviceWorker = _worker.Worker.from(worker);
132
133      serviceWorker._context = this;
134
135      this._serviceWorkers.add(serviceWorker);
136
137      this.emit(_events.Events.BrowserContext.ServiceWorker, serviceWorker);
138    });
139
140    this._channel.on('request', ({
141      request,
142      page
143    }) => this._onRequest(network.Request.from(request), _page.Page.fromNullable(page)));
144
145    this._channel.on('requestFailed', ({
146      request,
147      failureText,
148      responseEndTiming,
149      page
150    }) => this._onRequestFailed(network.Request.from(request), responseEndTiming, failureText, _page.Page.fromNullable(page)));
151
152    this._channel.on('requestFinished', params => this._onRequestFinished(params));
153
154    this._channel.on('response', ({
155      response,
156      page
157    }) => this._onResponse(network.Response.from(response), _page.Page.fromNullable(page)));
158
159    this._closedPromise = new Promise(f => this.once(_events.Events.BrowserContext.Close, f));
160  }
161
162  _setBrowserType(browserType) {
163    this._browserType = browserType;
164
165    browserType._contexts.add(this);
166  }
167
168  _onPage(page) {
169    this._pages.add(page);
170
171    this.emit(_events.Events.BrowserContext.Page, page);
172    if (page._opener && !page._opener.isClosed()) page._opener.emit(_events.Events.Page.Popup, page);
173  }
174
175  _onRequest(request, page) {
176    this.emit(_events.Events.BrowserContext.Request, request);
177    if (page) page.emit(_events.Events.Page.Request, request);
178  }
179
180  _onResponse(response, page) {
181    this.emit(_events.Events.BrowserContext.Response, response);
182    if (page) page.emit(_events.Events.Page.Response, response);
183  }
184
185  _onRequestFailed(request, responseEndTiming, failureText, page) {
186    request._failureText = failureText || null;
187    if (request._timing) request._timing.responseEnd = responseEndTiming;
188    this.emit(_events.Events.BrowserContext.RequestFailed, request);
189    if (page) page.emit(_events.Events.Page.RequestFailed, request);
190  }
191
192  _onRequestFinished(params) {
193    const {
194      responseEndTiming
195    } = params;
196    const request = network.Request.from(params.request);
197    const response = network.Response.fromNullable(params.response);
198
199    const page = _page.Page.fromNullable(params.page);
200
201    if (request._timing) request._timing.responseEnd = responseEndTiming;
202    this.emit(_events.Events.BrowserContext.RequestFinished, request);
203    if (page) page.emit(_events.Events.Page.RequestFinished, request);
204    if (response) response._finishedPromise.resolve();
205  }
206
207  _onRoute(route, request) {
208    for (const routeHandler of this._routes) {
209      if (routeHandler.matches(request.url())) {
210        try {
211          routeHandler.handle(route, request);
212        } finally {
213          if (!routeHandler.isActive()) {
214            this._routes.splice(this._routes.indexOf(routeHandler), 1);
215
216            if (!this._routes.length) this._wrapApiCall(() => this._disableInterception(), true).catch(() => {});
217          }
218        }
219
220        return;
221      }
222    } // it can race with BrowserContext.close() which then throws since its closed
223
224
225    route._internalContinue();
226  }
227
228  async _onBinding(bindingCall) {
229    const func = this._bindings.get(bindingCall._initializer.name);
230
231    if (!func) return;
232    await bindingCall.call(func);
233  }
234
235  setDefaultNavigationTimeout(timeout) {
236    this._timeoutSettings.setDefaultNavigationTimeout(timeout);
237
238    this._wrapApiCall(async () => {
239      this._channel.setDefaultNavigationTimeoutNoReply({
240        timeout
241      });
242    }, true);
243  }
244
245  setDefaultTimeout(timeout) {
246    this._timeoutSettings.setDefaultTimeout(timeout);
247
248    this._wrapApiCall(async () => {
249      this._channel.setDefaultTimeoutNoReply({
250        timeout
251      });
252    }, true);
253  }
254
255  browser() {
256    return this._browser;
257  }
258
259  pages() {
260    return [...this._pages];
261  }
262
263  async newPage() {
264    if (this._ownerPage) throw new Error('Please use browser.newContext()');
265    return _page.Page.from((await this._channel.newPage()).page);
266  }
267
268  async cookies(urls) {
269    if (!urls) urls = [];
270    if (urls && typeof urls === 'string') urls = [urls];
271    return (await this._channel.cookies({
272      urls: urls
273    })).cookies;
274  }
275
276  async addCookies(cookies) {
277    await this._channel.addCookies({
278      cookies
279    });
280  }
281
282  async clearCookies() {
283    await this._channel.clearCookies();
284  }
285
286  async grantPermissions(permissions, options) {
287    await this._channel.grantPermissions({
288      permissions,
289      ...options
290    });
291  }
292
293  async clearPermissions() {
294    await this._channel.clearPermissions();
295  }
296
297  async setGeolocation(geolocation) {
298    await this._channel.setGeolocation({
299      geolocation: geolocation || undefined
300    });
301  }
302
303  async setExtraHTTPHeaders(headers) {
304    network.validateHeaders(headers);
305    await this._channel.setExtraHTTPHeaders({
306      headers: (0, _utils.headersObjectToArray)(headers)
307    });
308  }
309
310  async setOffline(offline) {
311    await this._channel.setOffline({
312      offline
313    });
314  }
315
316  async setHTTPCredentials(httpCredentials) {
317    await this._channel.setHTTPCredentials({
318      httpCredentials: httpCredentials || undefined
319    });
320  }
321
322  async addInitScript(script, arg) {
323    const source = await (0, _clientHelper.evaluationScript)(script, arg);
324    await this._channel.addInitScript({
325      source
326    });
327  }
328
329  async _removeInitScripts() {
330    await this._channel.removeInitScripts();
331  }
332
333  async exposeBinding(name, callback, options = {}) {
334    await this._channel.exposeBinding({
335      name,
336      needsHandle: options.handle
337    });
338
339    this._bindings.set(name, callback);
340  }
341
342  async _removeExposedBindings() {
343    this._bindings.clear();
344
345    await this._channel.removeExposedBindings();
346  }
347
348  async exposeFunction(name, callback) {
349    await this._channel.exposeBinding({
350      name
351    });
352
353    const binding = (source, ...args) => callback(...args);
354
355    this._bindings.set(name, binding);
356  }
357
358  async route(url, handler, options = {}) {
359    this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times));
360
361    if (this._routes.length === 1) await this._channel.setNetworkInterceptionEnabled({
362      enabled: true
363    });
364  }
365
366  async unroute(url, handler) {
367    this._routes = this._routes.filter(route => route.url !== url || handler && route.handler !== handler);
368    if (!this._routes.length) await this._disableInterception();
369  }
370
371  async _unrouteAll() {
372    this._routes = [];
373    await this._disableInterception();
374  }
375
376  async _disableInterception() {
377    await this._channel.setNetworkInterceptionEnabled({
378      enabled: false
379    });
380  }
381
382  async waitForEvent(event, optionsOrPredicate = {}) {
383    return this._wrapApiCall(async () => {
384      const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);
385
386      const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;
387
388      const waiter = _waiter.Waiter.createForEvent(this, event);
389
390      waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
391      if (event !== _events.Events.BrowserContext.Close) waiter.rejectOnEvent(this, _events.Events.BrowserContext.Close, new Error('Context closed'));
392      const result = await waiter.waitForEvent(this, event, predicate);
393      waiter.dispose();
394      return result;
395    });
396  }
397
398  async storageState(options = {}) {
399    const state = await this._channel.storageState();
400
401    if (options.path) {
402      await (0, _fileUtils.mkdirIfNeeded)(options.path);
403      await _fs.default.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');
404    }
405
406    return state;
407  }
408
409  backgroundPages() {
410    return [...this._backgroundPages];
411  }
412
413  serviceWorkers() {
414    return [...this._serviceWorkers];
415  }
416
417  async newCDPSession(page) {
418    // channelOwner.ts's validation messages don't handle the pseudo-union type, so we're explicit here
419    if (!(page instanceof _page.Page) && !(page instanceof _frame.Frame)) throw new Error('page: expected Page or Frame');
420    const result = await this._channel.newCDPSession(page instanceof _page.Page ? {
421      page: page._channel
422    } : {
423      frame: page._channel
424    });
425    return _cdpSession.CDPSession.from(result.session);
426  }
427
428  _onClose() {
429    var _this$_browserType, _this$_browserType$_c;
430
431    if (this._browser) this._browser._contexts.delete(this);
432    (_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);
433    this.emit(_events.Events.BrowserContext.Close, this);
434  }
435
436  async close() {
437    try {
438      await this._wrapApiCall(async () => {
439        var _this$_browserType2, _this$_browserType2$_;
440
441        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));
442
443        if (this._options.recordHar) {
444          const har = await this._channel.harExport();
445
446          const artifact = _artifact.Artifact.from(har.artifact);
447
448          await artifact.saveAs(this._options.recordHar.path);
449          await artifact.delete();
450        }
451      }, true);
452      await this._channel.close();
453      await this._closedPromise;
454    } catch (e) {
455      if ((0, _errors.isSafeCloseError)(e)) return;
456      throw e;
457    }
458  }
459
460  async _enableRecorder(params) {
461    await this._channel.recorderSupplementEnable(params);
462  }
463
464  async _resetForReuse() {
465    await this._unrouteAll();
466    await this._removeInitScripts();
467    await this._removeExposedBindings();
468  }
469
470}
471
472exports.BrowserContext = BrowserContext;
473
474async function prepareStorageState(options) {
475  if (typeof options.storageState !== 'string') return options.storageState;
476
477  try {
478    return JSON.parse(await _fs.default.promises.readFile(options.storageState, 'utf8'));
479  } catch (e) {
480    (0, _stackTrace.rewriteErrorMessage)(e, `Error reading storage state from ${options.storageState}:\n` + e.message);
481    throw e;
482  }
483}
484
485async function prepareBrowserContextParams(options) {
486  if (options.videoSize && !options.videosPath) throw new Error(`"videoSize" option requires "videosPath" to be specified`);
487  if (options.extraHTTPHeaders) network.validateHeaders(options.extraHTTPHeaders);
488  const contextParams = { ...options,
489    viewport: options.viewport === null ? undefined : options.viewport,
490    noDefaultViewport: options.viewport === null,
491    extraHTTPHeaders: options.extraHTTPHeaders ? (0, _utils.headersObjectToArray)(options.extraHTTPHeaders) : undefined,
492    storageState: await prepareStorageState(options)
493  };
494
495  if (!contextParams.recordVideo && options.videosPath) {
496    contextParams.recordVideo = {
497      dir: options.videosPath,
498      size: options.videoSize
499    };
500  }
501
502  return contextParams;
503}
Full Screen

page.js

Source: page.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.Page = exports.BindingCall = void 0;
7
8var _events = require("./events");
9
10var _utils = require("../utils");
11
12var _timeoutSettings = require("../common/timeoutSettings");
13
14var _serializers = require("../protocol/serializers");
15
16var _accessibility = require("./accessibility");
17
18var _channelOwner = require("./channelOwner");
19
20var _consoleMessage = require("./consoleMessage");
21
22var _dialog = require("./dialog");
23
24var _download = require("./download");
25
26var _elementHandle = require("./elementHandle");
27
28var _worker = require("./worker");
29
30var _frame = require("./frame");
31
32var _input = require("./input");
33
34var _jsHandle = require("./jsHandle");
35
36var _network = require("./network");
37
38var _fileChooser = require("./fileChooser");
39
40var _buffer = require("buffer");
41
42var _coverage = require("./coverage");
43
44var _waiter = require("./waiter");
45
46var _fs = _interopRequireDefault(require("fs"));
47
48var _path = _interopRequireDefault(require("path"));
49
50var _clientHelper = require("./clientHelper");
51
52var _fileUtils = require("../utils/fileUtils");
53
54var _errors = require("../common/errors");
55
56var _video = require("./video");
57
58var _artifact = require("./artifact");
59
60function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
61
62/**
63 * Copyright 2017 Google Inc. All rights reserved.
64 * Modifications copyright (c) Microsoft Corporation.
65 *
66 * Licensed under the Apache License, Version 2.0 (the "License");
67 * you may not use this file except in compliance with the License.
68 * You may obtain a copy of the License at
69 *
70 *     http://www.apache.org/licenses/LICENSE-2.0
71 *
72 * Unless required by applicable law or agreed to in writing, software
73 * distributed under the License is distributed on an "AS IS" BASIS,
74 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
75 * See the License for the specific language governing permissions and
76 * limitations under the License.
77 */
78class Page extends _channelOwner.ChannelOwner {
79  static from(page) {
80    return page._object;
81  }
82
83  static fromNullable(page) {
84    return page ? Page.from(page) : null;
85  }
86
87  constructor(parent, type, guid, initializer) {
88    super(parent, type, guid, initializer);
89    this._browserContext = void 0;
90    this._ownedContext = void 0;
91    this._mainFrame = void 0;
92    this._frames = new Set();
93    this._workers = new Set();
94    this._closed = false;
95    this._closedOrCrashedPromise = void 0;
96    this._viewportSize = void 0;
97    this._routes = [];
98    this.accessibility = void 0;
99    this.coverage = void 0;
100    this.keyboard = void 0;
101    this.mouse = void 0;
102    this.request = void 0;
103    this.touchscreen = void 0;
104    this._bindings = new Map();
105    this._timeoutSettings = void 0;
106    this._video = null;
107    this._opener = void 0;
108    this._browserContext = parent;
109    this._timeoutSettings = new _timeoutSettings.TimeoutSettings(this._browserContext._timeoutSettings);
110    this.accessibility = new _accessibility.Accessibility(this._channel);
111    this.keyboard = new _input.Keyboard(this);
112    this.mouse = new _input.Mouse(this);
113    this.request = this._browserContext.request;
114    this.touchscreen = new _input.Touchscreen(this);
115    this._mainFrame = _frame.Frame.from(initializer.mainFrame);
116    this._mainFrame._page = this;
117
118    this._frames.add(this._mainFrame);
119
120    this._viewportSize = initializer.viewportSize || null;
121    this._closed = initializer.isClosed;
122    this._opener = Page.fromNullable(initializer.opener);
123
124    this._channel.on('bindingCall', ({
125      binding
126    }) => this._onBinding(BindingCall.from(binding)));
127
128    this._channel.on('close', () => this._onClose());
129
130    this._channel.on('console', ({
131      message
132    }) => this.emit(_events.Events.Page.Console, _consoleMessage.ConsoleMessage.from(message)));
133
134    this._channel.on('crash', () => this._onCrash());
135
136    this._channel.on('dialog', ({
137      dialog
138    }) => {
139      const dialogObj = _dialog.Dialog.from(dialog);
140
141      if (!this.emit(_events.Events.Page.Dialog, dialogObj)) {
142        if (dialogObj.type() === 'beforeunload') dialog.accept({}).catch(() => {});else dialog.dismiss().catch(() => {});
143      }
144    });
145
146    this._channel.on('domcontentloaded', () => this.emit(_events.Events.Page.DOMContentLoaded, this));
147
148    this._channel.on('download', ({
149      url,
150      suggestedFilename,
151      artifact
152    }) => {
153      const artifactObject = _artifact.Artifact.from(artifact);
154
155      this.emit(_events.Events.Page.Download, new _download.Download(this, url, suggestedFilename, artifactObject));
156    });
157
158    this._channel.on('fileChooser', ({
159      element,
160      isMultiple
161    }) => this.emit(_events.Events.Page.FileChooser, new _fileChooser.FileChooser(this, _elementHandle.ElementHandle.from(element), isMultiple)));
162
163    this._channel.on('frameAttached', ({
164      frame
165    }) => this._onFrameAttached(_frame.Frame.from(frame)));
166
167    this._channel.on('frameDetached', ({
168      frame
169    }) => this._onFrameDetached(_frame.Frame.from(frame)));
170
171    this._channel.on('load', () => this.emit(_events.Events.Page.Load, this));
172
173    this._channel.on('pageError', ({
174      error
175    }) => this.emit(_events.Events.Page.PageError, (0, _serializers.parseError)(error)));
176
177    this._channel.on('route', ({
178      route,
179      request
180    }) => this._onRoute(_network.Route.from(route), _network.Request.from(request)));
181
182    this._channel.on('video', ({
183      artifact
184    }) => {
185      const artifactObject = _artifact.Artifact.from(artifact);
186
187      this._forceVideo()._artifactReady(artifactObject);
188    });
189
190    this._channel.on('webSocket', ({
191      webSocket
192    }) => this.emit(_events.Events.Page.WebSocket, _network.WebSocket.from(webSocket)));
193
194    this._channel.on('worker', ({
195      worker
196    }) => this._onWorker(_worker.Worker.from(worker)));
197
198    this.coverage = new _coverage.Coverage(this._channel);
199    this._closedOrCrashedPromise = Promise.race([new Promise(f => this.once(_events.Events.Page.Close, f)), new Promise(f => this.once(_events.Events.Page.Crash, f))]);
200  }
201
202  _onFrameAttached(frame) {
203    frame._page = this;
204
205    this._frames.add(frame);
206
207    if (frame._parentFrame) frame._parentFrame._childFrames.add(frame);
208    this.emit(_events.Events.Page.FrameAttached, frame);
209  }
210
211  _onFrameDetached(frame) {
212    this._frames.delete(frame);
213
214    frame._detached = true;
215    if (frame._parentFrame) frame._parentFrame._childFrames.delete(frame);
216    this.emit(_events.Events.Page.FrameDetached, frame);
217  }
218
219  _onRoute(route, request) {
220    for (const routeHandler of this._routes) {
221      if (routeHandler.matches(request.url())) {
222        try {
223          routeHandler.handle(route, request);
224        } finally {
225          if (!routeHandler.isActive()) {
226            this._routes.splice(this._routes.indexOf(routeHandler), 1);
227
228            if (!this._routes.length) this._wrapApiCall(() => this._disableInterception(), true).catch(() => {});
229          }
230        }
231
232        return;
233      }
234    }
235
236    this._browserContext._onRoute(route, request);
237  }
238
239  async _onBinding(bindingCall) {
240    const func = this._bindings.get(bindingCall._initializer.name);
241
242    if (func) {
243      await bindingCall.call(func);
244      return;
245    }
246
247    await this._browserContext._onBinding(bindingCall);
248  }
249
250  _onWorker(worker) {
251    this._workers.add(worker);
252
253    worker._page = this;
254    this.emit(_events.Events.Page.Worker, worker);
255  }
256
257  _onClose() {
258    this._closed = true;
259
260    this._browserContext._pages.delete(this);
261
262    this._browserContext._backgroundPages.delete(this);
263
264    this.emit(_events.Events.Page.Close, this);
265  }
266
267  _onCrash() {
268    this.emit(_events.Events.Page.Crash, this);
269  }
270
271  context() {
272    return this._browserContext;
273  }
274
275  async opener() {
276    if (!this._opener || this._opener.isClosed()) return null;
277    return this._opener;
278  }
279
280  mainFrame() {
281    return this._mainFrame;
282  }
283
284  frame(frameSelector) {
285    const name = (0, _utils.isString)(frameSelector) ? frameSelector : frameSelector.name;
286    const url = (0, _utils.isObject)(frameSelector) ? frameSelector.url : undefined;
287    (0, _utils.assert)(name || url, 'Either name or url matcher should be specified');
288    return this.frames().find(f => {
289      if (name) return f.name() === name;
290      return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, f.url(), url);
291    }) || null;
292  }
293
294  frames() {
295    return [...this._frames];
296  }
297
298  setDefaultNavigationTimeout(timeout) {
299    this._timeoutSettings.setDefaultNavigationTimeout(timeout);
300
301    this._wrapApiCall(async () => {
302      this._channel.setDefaultNavigationTimeoutNoReply({
303        timeout
304      });
305    }, true);
306  }
307
308  setDefaultTimeout(timeout) {
309    this._timeoutSettings.setDefaultTimeout(timeout);
310
311    this._wrapApiCall(async () => {
312      this._channel.setDefaultTimeoutNoReply({
313        timeout
314      });
315    }, true);
316  }
317
318  _forceVideo() {
319    if (!this._video) this._video = new _video.Video(this, this._connection);
320    return this._video;
321  }
322
323  video() {
324    // Note: we are creating Video object lazily, because we do not know
325    // BrowserContextOptions when constructing the page - it is assigned
326    // too late during launchPersistentContext.
327    if (!this._browserContext._options.recordVideo) return null;
328    return this._forceVideo();
329  }
330
331  async $(selector, options) {
332    return this._mainFrame.$(selector, options);
333  }
334
335  async waitForSelector(selector, options) {
336    return this._mainFrame.waitForSelector(selector, options);
337  }
338
339  async dispatchEvent(selector, type, eventInit, options) {
340    return this._mainFrame.dispatchEvent(selector, type, eventInit, options);
341  }
342
343  async evaluateHandle(pageFunction, arg) {
344    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);
345    return this._mainFrame.evaluateHandle(pageFunction, arg);
346  }
347
348  async $eval(selector, pageFunction, arg) {
349    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);
350    return this._mainFrame.$eval(selector, pageFunction, arg);
351  }
352
353  async $$eval(selector, pageFunction, arg) {
354    (0, _jsHandle.assertMaxArguments)(arguments.length, 3);
355    return this._mainFrame.$$eval(selector, pageFunction, arg);
356  }
357
358  async $$(selector) {
359    return this._mainFrame.$$(selector);
360  }
361
362  async addScriptTag(options = {}) {
363    return this._mainFrame.addScriptTag(options);
364  }
365
366  async addStyleTag(options = {}) {
367    return this._mainFrame.addStyleTag(options);
368  }
369
370  async exposeFunction(name, callback) {
371    await this._channel.exposeBinding({
372      name
373    });
374
375    const binding = (source, ...args) => callback(...args);
376
377    this._bindings.set(name, binding);
378  }
379
380  async exposeBinding(name, callback, options = {}) {
381    await this._channel.exposeBinding({
382      name,
383      needsHandle: options.handle
384    });
385
386    this._bindings.set(name, callback);
387  }
388
389  async _removeExposedBindings() {
390    this._bindings.clear();
391
392    await this._channel.removeExposedBindings();
393  }
394
395  async setExtraHTTPHeaders(headers) {
396    (0, _network.validateHeaders)(headers);
397    await this._channel.setExtraHTTPHeaders({
398      headers: (0, _utils.headersObjectToArray)(headers)
399    });
400  }
401
402  url() {
403    return this._mainFrame.url();
404  }
405
406  async content() {
407    return this._mainFrame.content();
408  }
409
410  async setContent(html, options) {
411    return this._mainFrame.setContent(html, options);
412  }
413
414  async goto(url, options) {
415    return this._mainFrame.goto(url, options);
416  }
417
418  async reload(options = {}) {
419    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
420    return _network.Response.fromNullable((await this._channel.reload({ ...options,
421      waitUntil
422    })).response);
423  }
424
425  async waitForLoadState(state, options) {
426    return this._mainFrame.waitForLoadState(state, options);
427  }
428
429  async waitForNavigation(options) {
430    return this._mainFrame.waitForNavigation(options);
431  }
432
433  async waitForURL(url, options) {
434    return this._mainFrame.waitForURL(url, options);
435  }
436
437  async waitForRequest(urlOrPredicate, options = {}) {
438    const predicate = request => {
439      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);
440      return urlOrPredicate(request);
441    };
442
443    const trimmedUrl = trimUrl(urlOrPredicate);
444    const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : undefined;
445    return this._waitForEvent(_events.Events.Page.Request, {
446      predicate,
447      timeout: options.timeout
448    }, logLine);
449  }
450
451  async waitForResponse(urlOrPredicate, options = {}) {
452    const predicate = response => {
453      if ((0, _utils.isString)(urlOrPredicate) || (0, _utils.isRegExp)(urlOrPredicate)) return (0, _clientHelper.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);
454      return urlOrPredicate(response);
455    };
456
457    const trimmedUrl = trimUrl(urlOrPredicate);
458    const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : undefined;
459    return this._waitForEvent(_events.Events.Page.Response, {
460      predicate,
461      timeout: options.timeout
462    }, logLine);
463  }
464
465  async waitForEvent(event, optionsOrPredicate = {}) {
466    return this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);
467  }
468
469  async _waitForEvent(event, optionsOrPredicate, logLine) {
470    return this._wrapApiCall(async () => {
471      const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);
472
473      const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;
474
475      const waiter = _waiter.Waiter.createForEvent(this, event);
476
477      if (logLine) waiter.log(logLine);
478      waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
479      if (event !== _events.Events.Page.Crash) waiter.rejectOnEvent(this, _events.Events.Page.Crash, new Error('Page crashed'));
480      if (event !== _events.Events.Page.Close) waiter.rejectOnEvent(this, _events.Events.Page.Close, new Error('Page closed'));
481      const result = await waiter.waitForEvent(this, event, predicate);
482      waiter.dispose();
483      return result;
484    });
485  }
486
487  async goBack(options = {}) {
488    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
489    return _network.Response.fromNullable((await this._channel.goBack({ ...options,
490      waitUntil
491    })).response);
492  }
493
494  async goForward(options = {}) {
495    const waitUntil = (0, _frame.verifyLoadState)('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
496    return _network.Response.fromNullable((await this._channel.goForward({ ...options,
497      waitUntil
498    })).response);
499  }
500
501  async emulateMedia(options = {}) {
502    await this._channel.emulateMedia({
503      media: options.media === null ? 'null' : options.media,
504      colorScheme: options.colorScheme === null ? 'null' : options.colorScheme,
505      reducedMotion: options.reducedMotion === null ? 'null' : options.reducedMotion,
506      forcedColors: options.forcedColors === null ? 'null' : options.forcedColors
507    });
508  }
509
510  async setViewportSize(viewportSize) {
511    this._viewportSize = viewportSize;
512    await this._channel.setViewportSize({
513      viewportSize
514    });
515  }
516
517  viewportSize() {
518    return this._viewportSize;
519  }
520
521  async evaluate(pageFunction, arg) {
522    (0, _jsHandle.assertMaxArguments)(arguments.length, 2);
523    return this._mainFrame.evaluate(pageFunction, arg);
524  }
525
526  async addInitScript(script, arg) {
527    const source = await (0, _clientHelper.evaluationScript)(script, arg);
528    await this._channel.addInitScript({
529      source
530    });
531  }
532
533  async _removeInitScripts() {
534    await this._channel.removeInitScripts();
535  }
536
537  async route(url, handler, options = {}) {
538    this._routes.unshift(new _network.RouteHandler(this._browserContext._options.baseURL, url, handler, options.times));
539
540    if (this._routes.length === 1) await this._channel.setNetworkInterceptionEnabled({
541      enabled: true
542    });
543  }
544
545  async unroute(url, handler) {
546    this._routes = this._routes.filter(route => route.url !== url || handler && route.handler !== handler);
547    if (!this._routes.length) await this._disableInterception();
548  }
549
550  async _unrouteAll() {
551    this._routes = [];
552    await this._disableInterception();
553  }
554
555  async _disableInterception() {
556    await this._channel.setNetworkInterceptionEnabled({
557      enabled: false
558    });
559  }
560
561  async screenshot(options = {}) {
562    const copy = { ...options,
563      mask: undefined
564    };
565    if (!copy.type) copy.type = (0, _elementHandle.determineScreenshotType)(options);
566
567    if (options.mask) {
568      copy.mask = options.mask.map(locator => ({
569        frame: locator._frame._channel,
570        selector: locator._selector
571      }));
572    }
573
574    copy.fonts = options._fonts;
575    const result = await this._channel.screenshot(copy);
576
577    const buffer = _buffer.Buffer.from(result.binary, 'base64');
578
579    if (options.path) {
580      await (0, _fileUtils.mkdirIfNeeded)(options.path);
581      await _fs.default.promises.writeFile(options.path, buffer);
582    }
583
584    return buffer;
585  }
586
587  async _expectScreenshot(customStackTrace, options) {
588    return this._wrapApiCall(async () => {
589      var _options$screenshotOp, _options$screenshotOp2;
590
591      const mask = (_options$screenshotOp = options.screenshotOptions) !== null && _options$screenshotOp !== void 0 && _options$screenshotOp.mask ? (_options$screenshotOp2 = options.screenshotOptions) === null || _options$screenshotOp2 === void 0 ? void 0 : _options$screenshotOp2.mask.map(locator => ({
592        frame: locator._frame._channel,
593        selector: locator._selector
594      })) : undefined;
595      const locator = options.locator ? {
596        frame: options.locator._frame._channel,
597        selector: options.locator._selector
598      } : undefined;
599      const expected = options.expected ? options.expected.toString('base64') : undefined;
600      const result = await this._channel.expectScreenshot({ ...options,
601        isNot: !!options.isNot,
602        expected,
603        locator,
604        screenshotOptions: { ...options.screenshotOptions,
605          mask
606        }
607      });
608      return {
609        log: result.log,
610        actual: result.actual ? _buffer.Buffer.from(result.actual, 'base64') : undefined,
611        previous: result.previous ? _buffer.Buffer.from(result.previous, 'base64') : undefined,
612        diff: result.diff ? _buffer.Buffer.from(result.diff, 'base64') : undefined,
613        errorMessage: result.errorMessage
614      };
615    }, false
616    /* isInternal */
617    , customStackTrace);
618  }
619
620  async title() {
621    return this._mainFrame.title();
622  }
623
624  async bringToFront() {
625    await this._channel.bringToFront();
626  }
627
628  async close(options = {
629    runBeforeUnload: undefined
630  }) {
631    try {
632      if (this._ownedContext) await this._ownedContext.close();else await this._channel.close(options);
633    } catch (e) {
634      if ((0, _errors.isSafeCloseError)(e)) return;
635      throw e;
636    }
637  }
638
639  isClosed() {
640    return this._closed;
641  }
642
643  async click(selector, options) {
644    return this._mainFrame.click(selector, options);
645  }
646
647  async dragAndDrop(source, target, options) {
648    return this._mainFrame.dragAndDrop(source, target, options);
649  }
650
651  async dblclick(selector, options) {
652    return this._mainFrame.dblclick(selector, options);
653  }
654
655  async tap(selector, options) {
656    return this._mainFrame.tap(selector, options);
657  }
658
659  async fill(selector, value, options) {
660    return this._mainFrame.fill(selector, value, options);
661  }
662
663  locator(selector, options) {
664    return this.mainFrame().locator(selector, options);
665  }
666
667  frameLocator(selector) {
668    return this.mainFrame().frameLocator(selector);
669  }
670
671  async focus(selector, options) {
672    return this._mainFrame.focus(selector, options);
673  }
674
675  async textContent(selector, options) {
676    return this._mainFrame.textContent(selector, options);
677  }
678
679  async innerText(selector, options) {
680    return this._mainFrame.innerText(selector, options);
681  }
682
683  async innerHTML(selector, options) {
684    return this._mainFrame.innerHTML(selector, options);
685  }
686
687  async getAttribute(selector, name, options) {
688    return this._mainFrame.getAttribute(selector, name, options);
689  }
690
691  async inputValue(selector, options) {
692    return this._mainFrame.inputValue(selector, options);
693  }
694
695  async isChecked(selector, options) {
696    return this._mainFrame.isChecked(selector, options);
697  }
698
699  async isDisabled(selector, options) {
700    return this._mainFrame.isDisabled(selector, options);
701  }
702
703  async isEditable(selector, options) {
704    return this._mainFrame.isEditable(selector, options);
705  }
706
707  async isEnabled(selector, options) {
708    return this._mainFrame.isEnabled(selector, options);
709  }
710
711  async isHidden(selector, options) {
712    return this._mainFrame.isHidden(selector, options);
713  }
714
715  async isVisible(selector, options) {
716    return this._mainFrame.isVisible(selector, options);
717  }
718
719  async hover(selector, options) {
720    return this._mainFrame.hover(selector, options);
721  }
722
723  async selectOption(selector, values, options) {
724    return this._mainFrame.selectOption(selector, values, options);
725  }
726
727  async setInputFiles(selector, files, options) {
728    return this._mainFrame.setInputFiles(selector, files, options);
729  }
730
731  async type(selector, text, options) {
732    return this._mainFrame.type(selector, text, options);
733  }
734
735  async press(selector, key, options) {
736    return this._mainFrame.press(selector, key, options);
737  }
738
739  async check(selector, options) {
740    return this._mainFrame.check(selector, options);
741  }
742
743  async uncheck(selector, options) {
744    return this._mainFrame.uncheck(selector, options);
745  }
746
747  async setChecked(selector, checked, options) {
748    return this._mainFrame.setChecked(selector, checked, options);
749  }
750
751  async waitForTimeout(timeout) {
752    return this._mainFrame.waitForTimeout(timeout);
753  }
754
755  async waitForFunction(pageFunction, arg, options) {
756    return this._mainFrame.waitForFunction(pageFunction, arg, options);
757  }
758
759  workers() {
760    return [...this._workers];
761  }
762
763  on(event, listener) {
764    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({
765      intercepted: true
766    });
767    super.on(event, listener);
768    return this;
769  }
770
771  addListener(event, listener) {
772    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({
773      intercepted: true
774    });
775    super.addListener(event, listener);
776    return this;
777  }
778
779  off(event, listener) {
780    super.off(event, listener);
781    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({
782      intercepted: false
783    });
784    return this;
785  }
786
787  removeListener(event, listener) {
788    super.removeListener(event, listener);
789    if (event === _events.Events.Page.FileChooser && !this.listenerCount(event)) this._channel.setFileChooserInterceptedNoReply({
790      intercepted: false
791    });
792    return this;
793  }
794
795  async pause() {
796    if (!require('inspector').url()) await this.context()._channel.pause();
797  }
798
799  async pdf(options = {}) {
800    const transportOptions = { ...options
801    };
802    if (transportOptions.margin) transportOptions.margin = { ...transportOptions.margin
803    };
804    if (typeof options.width === 'number') transportOptions.width = options.width + 'px';
805    if (typeof options.height === 'number') transportOptions.height = options.height + 'px';
806
807    for (const margin of ['top', 'right', 'bottom', 'left']) {
808      const index = margin;
809      if (options.margin && typeof options.margin[index] === 'number') transportOptions.margin[index] = transportOptions.margin[index] + 'px';
810    }
811
812    const result = await this._channel.pdf(transportOptions);
813
814    const buffer = _buffer.Buffer.from(result.pdf, 'base64');
815
816    if (options.path) {
817      await _fs.default.promises.mkdir(_path.default.dirname(options.path), {
818        recursive: true
819      });
820      await _fs.default.promises.writeFile(options.path, buffer);
821    }
822
823    return buffer;
824  }
825
826  async _resetForReuse() {
827    await this._unrouteAll();
828    await this._removeInitScripts();
829    await this._removeExposedBindings();
830  }
831
832}
833
834exports.Page = Page;
835
836class BindingCall extends _channelOwner.ChannelOwner {
837  static from(channel) {
838    return channel._object;
839  }
840
841  constructor(parent, type, guid, initializer) {
842    super(parent, type, guid, initializer);
843  }
844
845  async call(func) {
846    try {
847      const frame = _frame.Frame.from(this._initializer.frame);
848
849      const source = {
850        context: frame._page.context(),
851        page: frame._page,
852        frame
853      };
854      let result;
855      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));
856
857      this._channel.resolve({
858        result: (0, _jsHandle.serializeArgument)(result)
859      }).catch(() => {});
860    } catch (e) {
861      this._channel.reject({
862        error: (0, _serializers.serializeError)(e)
863      }).catch(() => {});
864    }
865  }
866
867}
868
869exports.BindingCall = BindingCall;
870
871function trimEnd(s) {
872  if (s.length > 50) s = s.substring(0, 50) + '\u2026';
873  return s;
874}
875
876function trimUrl(param) {
877  if ((0, _utils.isRegExp)(param)) return `/${trimEnd(param.source)}/${param.flags}`;
878  if ((0, _utils.isString)(param)) return `"${trimEnd(param)}"`;
879}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)