How to use updateHttpCredentials 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.

wkBrowser.js

Source: wkBrowser.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.WKBrowserContext = exports.WKBrowser = void 0;
7
8var _browser = require("../browser");
9
10var _browserContext = require("../browserContext");
11
12var _eventsHelper = require("../../utils/eventsHelper");
13
14var _utils = require("../../utils/utils");
15
16var network = _interopRequireWildcard(require("../network"));
17
18var _wkConnection = require("./wkConnection");
19
20var _wkPage = require("./wkPage");
21
22var _errors = require("../../utils/errors");
23
24function _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); }
25
26function _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; }
27
28/**
29 * Copyright 2017 Google Inc. All rights reserved.
30 * Modifications copyright (c) Microsoft Corporation.
31 *
32 * Licensed under the Apache License, Version 2.0 (the "License");
33 * you may not use this file except in compliance with the License.
34 * You may obtain a copy of the License at
35 *
36 *     http://www.apache.org/licenses/LICENSE-2.0
37 *
38 * Unless required by applicable law or agreed to in writing, software
39 * distributed under the License is distributed on an "AS IS" BASIS,
40 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
41 * See the License for the specific language governing permissions and
42 * limitations under the License.
43 */
44const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15';
45const BROWSER_VERSION = '15.4';
46
47class WKBrowser extends _browser.Browser {
48  static async connect(transport, options) {
49    const browser = new WKBrowser(transport, options);
50    if (options.__testHookOnConnectToBrowser) await options.__testHookOnConnectToBrowser();
51    const promises = [browser._browserSession.send('Playwright.enable')];
52
53    if (options.persistent) {
54      browser._defaultContext = new WKBrowserContext(browser, undefined, options.persistent);
55      promises.push(browser._defaultContext._initialize());
56    }
57
58    await Promise.all(promises);
59    return browser;
60  }
61
62  constructor(transport, options) {
63    super(options);
64    this._connection = void 0;
65    this._browserSession = void 0;
66    this._contexts = new Map();
67    this._wkPages = new Map();
68    this._eventListeners = void 0;
69    this._connection = new _wkConnection.WKConnection(transport, this._onDisconnect.bind(this), options.protocolLogger, options.browserLogsCollector);
70    this._browserSession = this._connection.browserSession;
71    this._eventListeners = [_eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.pageProxyCreated', this._onPageProxyCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.pageProxyDestroyed', this._onPageProxyDestroyed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.provisionalLoadFailed', event => this._onProvisionalLoadFailed(event)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.windowOpen', event => this._onWindowOpen(event)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadCreated', this._onDownloadCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadFilenameSuggested', this._onDownloadFilenameSuggested.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.downloadFinished', this._onDownloadFinished.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, 'Playwright.screencastFinished', this._onScreencastFinished.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._browserSession, _wkConnection.kPageProxyMessageReceived, this._onPageProxyMessageReceived.bind(this))];
72  }
73
74  _onDisconnect() {
75    for (const wkPage of this._wkPages.values()) wkPage.dispose(true);
76
77    for (const video of this._idToVideo.values()) video.artifact.reportFinished(_errors.kBrowserClosedError);
78
79    this._idToVideo.clear();
80
81    this._didClose();
82  }
83
84  async newContext(options) {
85    (0, _browserContext.validateBrowserContextOptions)(options, this.options);
86    const createOptions = options.proxy ? {
87      proxyServer: options.proxy.server,
88      proxyBypassList: options.proxy.bypass
89    } : undefined;
90    const {
91      browserContextId
92    } = await this._browserSession.send('Playwright.createContext', createOptions);
93    options.userAgent = options.userAgent || DEFAULT_USER_AGENT;
94    const context = new WKBrowserContext(this, browserContextId, options);
95    await context._initialize();
96
97    this._contexts.set(browserContextId, context);
98
99    return context;
100  }
101
102  contexts() {
103    return Array.from(this._contexts.values());
104  }
105
106  version() {
107    return BROWSER_VERSION;
108  }
109
110  userAgent() {
111    return DEFAULT_USER_AGENT;
112  }
113
114  _onDownloadCreated(payload) {
115    const page = this._wkPages.get(payload.pageProxyId);
116
117    if (!page) return; // In some cases, e.g. blob url download, we receive only frameScheduledNavigation
118    // but no signals that the navigation was canceled and replaced by download. Fix it
119    // here by simulating cancelled provisional load which matches downloads from network.
120    //
121    // TODO: this is racy, because download might be unrelated any navigation, and we will
122    // abort navgitation that is still running. We should be able to fix this by
123    // instrumenting policy decision start/proceed/cancel.
124
125    page._page._frameManager.frameAbortedNavigation(payload.frameId, 'Download is starting');
126
127    let originPage = page._initializedPage; // If it's a new window download, report it on the opener page.
128
129    if (!originPage) {
130      // Resume the page creation with an error. The page will automatically close right
131      // after the download begins.
132      page._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));
133
134      if (page._opener) originPage = page._opener._initializedPage;
135    }
136
137    if (!originPage) return;
138
139    this._downloadCreated(originPage, payload.uuid, payload.url);
140  }
141
142  _onDownloadFilenameSuggested(payload) {
143    this._downloadFilenameSuggested(payload.uuid, payload.suggestedFilename);
144  }
145
146  _onDownloadFinished(payload) {
147    this._downloadFinished(payload.uuid, payload.error);
148  }
149
150  _onScreencastFinished(payload) {
151    var _this$_takeVideo;
152
153    (_this$_takeVideo = this._takeVideo(payload.screencastId)) === null || _this$_takeVideo === void 0 ? void 0 : _this$_takeVideo.reportFinished();
154  }
155
156  _onPageProxyCreated(event) {
157    const pageProxyId = event.pageProxyId;
158    let context = null;
159
160    if (event.browserContextId) {
161      // FIXME: we don't know about the default context id, so assume that all targets from
162      // unknown contexts are created in the 'default' context which can in practice be represented
163      // by multiple actual contexts in WebKit. Solving this properly will require adding context
164      // lifecycle events.
165      context = this._contexts.get(event.browserContextId) || null;
166    }
167
168    if (!context) context = this._defaultContext;
169    if (!context) return;
170    const pageProxySession = new _wkConnection.WKSession(this._connection, pageProxyId, `Target closed`, message => {
171      this._connection.rawSend({ ...message,
172        pageProxyId
173      });
174    });
175    const opener = event.openerId ? this._wkPages.get(event.openerId) : undefined;
176    const wkPage = new _wkPage.WKPage(context, pageProxySession, opener || null);
177
178    this._wkPages.set(pageProxyId, wkPage);
179  }
180
181  _onPageProxyDestroyed(event) {
182    const pageProxyId = event.pageProxyId;
183
184    const wkPage = this._wkPages.get(pageProxyId);
185
186    if (!wkPage) return;
187    wkPage.didClose();
188    wkPage.dispose(false);
189
190    this._wkPages.delete(pageProxyId);
191  }
192
193  _onPageProxyMessageReceived(event) {
194    const wkPage = this._wkPages.get(event.pageProxyId);
195
196    if (!wkPage) return;
197    wkPage.dispatchMessageToSession(event.message);
198  }
199
200  _onProvisionalLoadFailed(event) {
201    const wkPage = this._wkPages.get(event.pageProxyId);
202
203    if (!wkPage) return;
204    wkPage.handleProvisionalLoadFailed(event);
205  }
206
207  _onWindowOpen(event) {
208    const wkPage = this._wkPages.get(event.pageProxyId);
209
210    if (!wkPage) return;
211    wkPage.handleWindowOpen(event);
212  }
213
214  isConnected() {
215    return !this._connection.isClosed();
216  }
217
218}
219
220exports.WKBrowser = WKBrowser;
221
222class WKBrowserContext extends _browserContext.BrowserContext {
223  constructor(browser, browserContextId, options) {
224    super(browser, options, browserContextId);
225    this._evaluateOnNewDocumentSources = void 0;
226    this._evaluateOnNewDocumentSources = [];
227
228    this._authenticateProxyViaHeader();
229  }
230
231  async _initialize() {
232    (0, _utils.assert)(!this._wkPages().length);
233    const browserContextId = this._browserContextId;
234    const promises = [super._initialize()];
235    promises.push(this._browser._browserSession.send('Playwright.setDownloadBehavior', {
236      behavior: this._options.acceptDownloads ? 'allow' : 'deny',
237      downloadPath: this._browser.options.downloadsPath,
238      browserContextId
239    }));
240    if (this._options.ignoreHTTPSErrors) promises.push(this._browser._browserSession.send('Playwright.setIgnoreCertificateErrors', {
241      browserContextId,
242      ignore: true
243    }));
244    if (this._options.locale) promises.push(this._browser._browserSession.send('Playwright.setLanguages', {
245      browserContextId,
246      languages: [this._options.locale]
247    }));
248    if (this._options.permissions) promises.push(this.grantPermissions(this._options.permissions));
249    if (this._options.geolocation) promises.push(this.setGeolocation(this._options.geolocation));
250    if (this._options.offline) promises.push(this.setOffline(this._options.offline));
251    if (this._options.httpCredentials) promises.push(this.setHTTPCredentials(this._options.httpCredentials));
252    await Promise.all(promises);
253  }
254
255  _wkPages() {
256    return Array.from(this._browser._wkPages.values()).filter(wkPage => wkPage._browserContext === this);
257  }
258
259  pages() {
260    return this._wkPages().map(wkPage => wkPage._initializedPage).filter(pageOrNull => !!pageOrNull);
261  }
262
263  async newPageDelegate() {
264    (0, _browserContext.assertBrowserContextIsNotOwned)(this);
265    const {
266      pageProxyId
267    } = await this._browser._browserSession.send('Playwright.createPage', {
268      browserContextId: this._browserContextId
269    });
270    return this._browser._wkPages.get(pageProxyId);
271  }
272
273  async _doCookies(urls) {
274    const {
275      cookies
276    } = await this._browser._browserSession.send('Playwright.getAllCookies', {
277      browserContextId: this._browserContextId
278    });
279    return network.filterCookies(cookies.map(c => {
280      const copy = { ...c
281      };
282      copy.expires = c.expires === -1 ? -1 : c.expires / 1000;
283      delete copy.session;
284      return copy;
285    }), urls);
286  }
287
288  async addCookies(cookies) {
289    const cc = network.rewriteCookies(cookies).map(c => ({ ...c,
290      session: c.expires === -1 || c.expires === undefined,
291      expires: c.expires && c.expires !== -1 ? c.expires * 1000 : c.expires
292    }));
293    await this._browser._browserSession.send('Playwright.setCookies', {
294      cookies: cc,
295      browserContextId: this._browserContextId
296    });
297  }
298
299  async clearCookies() {
300    await this._browser._browserSession.send('Playwright.deleteAllCookies', {
301      browserContextId: this._browserContextId
302    });
303  }
304
305  async _doGrantPermissions(origin, permissions) {
306    await Promise.all(this.pages().map(page => page._delegate._grantPermissions(origin, permissions)));
307  }
308
309  async _doClearPermissions() {
310    await Promise.all(this.pages().map(page => page._delegate._clearPermissions()));
311  }
312
313  async setGeolocation(geolocation) {
314    (0, _browserContext.verifyGeolocation)(geolocation);
315    this._options.geolocation = geolocation;
316    const payload = geolocation ? { ...geolocation,
317      timestamp: Date.now()
318    } : undefined;
319    await this._browser._browserSession.send('Playwright.setGeolocationOverride', {
320      browserContextId: this._browserContextId,
321      geolocation: payload
322    });
323  }
324
325  async setExtraHTTPHeaders(headers) {
326    this._options.extraHTTPHeaders = headers;
327
328    for (const page of this.pages()) await page._delegate.updateExtraHTTPHeaders();
329  }
330
331  async setOffline(offline) {
332    this._options.offline = offline;
333
334    for (const page of this.pages()) await page._delegate.updateOffline();
335  }
336
337  async _doSetHTTPCredentials(httpCredentials) {
338    this._options.httpCredentials = httpCredentials;
339
340    for (const page of this.pages()) await page._delegate.updateHttpCredentials();
341  }
342
343  async _doAddInitScript(source) {
344    this._evaluateOnNewDocumentSources.push(source);
345
346    for (const page of this.pages()) await page._delegate._updateBootstrapScript();
347  }
348
349  async _doExposeBinding(binding) {
350    for (const page of this.pages()) await page._delegate.exposeBinding(binding);
351  }
352
353  async _doUpdateRequestInterception() {
354    for (const page of this.pages()) await page._delegate.updateRequestInterception();
355  }
356
357  _onClosePersistent() {}
358
359  async _doClose() {
360    (0, _utils.assert)(this._browserContextId);
361    await this._browser._browserSession.send('Playwright.deleteContext', {
362      browserContextId: this._browserContextId
363    });
364
365    this._browser._contexts.delete(this._browserContextId);
366  }
367
368  async _doCancelDownload(uuid) {
369    await this._browser._browserSession.send('Playwright.cancelDownload', {
370      uuid
371    });
372  }
373
374}
375
376exports.WKBrowserContext = WKBrowserContext;
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)