browserContext.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var browserContext_exports = {};
  30. __export(browserContext_exports, {
  31. BrowserContext: () => BrowserContext,
  32. normalizeProxySettings: () => normalizeProxySettings,
  33. validateBrowserContextOptions: () => validateBrowserContextOptions,
  34. verifyClientCertificates: () => verifyClientCertificates,
  35. verifyGeolocation: () => verifyGeolocation
  36. });
  37. module.exports = __toCommonJS(browserContext_exports);
  38. var import_fs = __toESM(require("fs"));
  39. var import_path = __toESM(require("path"));
  40. var import_crypto = require("./utils/crypto");
  41. var import_debug = require("./utils/debug");
  42. var import_clock = require("./clock");
  43. var import_debugger = require("./debugger");
  44. var import_dialog = require("./dialog");
  45. var import_fetch = require("./fetch");
  46. var import_fileUtils = require("./utils/fileUtils");
  47. var import_stackTrace = require("../utils/isomorphic/stackTrace");
  48. var import_harRecorder = require("./har/harRecorder");
  49. var import_helper = require("./helper");
  50. var import_instrumentation = require("./instrumentation");
  51. var network = __toESM(require("./network"));
  52. var import_page = require("./page");
  53. var import_page2 = require("./page");
  54. var import_recorderApp = require("./recorder/recorderApp");
  55. var import_selectors = require("./selectors");
  56. var import_tracing = require("./trace/recorder/tracing");
  57. var rawStorageSource = __toESM(require("../generated/storageScriptSource"));
  58. class BrowserContext extends import_instrumentation.SdkObject {
  59. constructor(browser, options, browserContextId) {
  60. super(browser, "browser-context");
  61. this._pageBindings = /* @__PURE__ */ new Map();
  62. this.requestInterceptors = [];
  63. this._closedStatus = "open";
  64. this._permissions = /* @__PURE__ */ new Map();
  65. this._downloads = /* @__PURE__ */ new Set();
  66. this._origins = /* @__PURE__ */ new Set();
  67. this._harRecorders = /* @__PURE__ */ new Map();
  68. this._tempDirs = [];
  69. this._creatingStorageStatePage = false;
  70. this.initScripts = [];
  71. this._routesInFlight = /* @__PURE__ */ new Set();
  72. this.attribution.context = this;
  73. this._browser = browser;
  74. this._options = options;
  75. this._browserContextId = browserContextId;
  76. this._isPersistentContext = !browserContextId;
  77. this._closePromise = new Promise((fulfill) => this._closePromiseFulfill = fulfill);
  78. this._selectors = new import_selectors.Selectors(options.selectorEngines || [], options.testIdAttributeName);
  79. this.fetchRequest = new import_fetch.BrowserContextAPIRequestContext(this);
  80. this.tracing = new import_tracing.Tracing(this, browser.options.tracesDir);
  81. this.clock = new import_clock.Clock(this);
  82. this.dialogManager = new import_dialog.DialogManager(this.instrumentation);
  83. }
  84. static {
  85. this.Events = {
  86. Console: "console",
  87. Close: "close",
  88. Page: "page",
  89. // Can't use just 'error' due to node.js special treatment of error events.
  90. // @see https://nodejs.org/api/events.html#events_error_events
  91. PageError: "pageerror",
  92. Request: "request",
  93. Response: "response",
  94. RequestFailed: "requestfailed",
  95. RequestFinished: "requestfinished",
  96. RequestAborted: "requestaborted",
  97. RequestFulfilled: "requestfulfilled",
  98. RequestContinued: "requestcontinued",
  99. BeforeClose: "beforeclose",
  100. VideoStarted: "videostarted",
  101. RecorderEvent: "recorderevent"
  102. };
  103. }
  104. isPersistentContext() {
  105. return this._isPersistentContext;
  106. }
  107. selectors() {
  108. return this._selectors;
  109. }
  110. async _initialize() {
  111. if (this.attribution.playwright.options.isInternalPlaywright)
  112. return;
  113. this._debugger = new import_debugger.Debugger(this);
  114. if ((0, import_debug.debugMode)() === "inspector")
  115. await import_recorderApp.RecorderApp.show(this, { pauseOnNextStatement: true });
  116. if (this._debugger.isPaused())
  117. import_recorderApp.RecorderApp.showInspectorNoReply(this);
  118. this._debugger.on(import_debugger.Debugger.Events.PausedStateChanged, () => {
  119. if (this._debugger.isPaused())
  120. import_recorderApp.RecorderApp.showInspectorNoReply(this);
  121. });
  122. if ((0, import_debug.debugMode)() === "console") {
  123. await this.extendInjectedScript(`
  124. function installConsoleApi(injectedScript) { injectedScript.consoleApi.install(); }
  125. module.exports = { default: () => installConsoleApi };
  126. `);
  127. }
  128. if (this._options.serviceWorkers === "block")
  129. await this.addInitScript(void 0, `
  130. if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };
  131. `);
  132. if (this._options.permissions)
  133. await this.grantPermissions(this._options.permissions);
  134. }
  135. debugger() {
  136. return this._debugger;
  137. }
  138. async _ensureVideosPath() {
  139. if (this._options.recordVideo)
  140. await (0, import_fileUtils.mkdirIfNeeded)(import_path.default.join(this._options.recordVideo.dir, "dummy"));
  141. }
  142. canResetForReuse() {
  143. if (this._closedStatus !== "open")
  144. return false;
  145. return true;
  146. }
  147. static reusableContextHash(params) {
  148. const paramsCopy = { ...params };
  149. if (paramsCopy.selectorEngines?.length === 0)
  150. delete paramsCopy.selectorEngines;
  151. for (const k of Object.keys(paramsCopy)) {
  152. const key = k;
  153. if (paramsCopy[key] === defaultNewContextParamValues[key])
  154. delete paramsCopy[key];
  155. }
  156. for (const key of paramsThatAllowContextReuse)
  157. delete paramsCopy[key];
  158. return JSON.stringify(paramsCopy);
  159. }
  160. async resetForReuse(progress, params) {
  161. await this.tracing.resetForReuse(progress);
  162. if (params) {
  163. for (const key of paramsThatAllowContextReuse)
  164. this._options[key] = params[key];
  165. if (params.testIdAttributeName)
  166. this.selectors().setTestIdAttributeName(params.testIdAttributeName);
  167. }
  168. let page = this.pages()[0];
  169. const otherPages = this.possiblyUninitializedPages().filter((p) => p !== page);
  170. for (const p of otherPages)
  171. await p.close();
  172. if (page && page.hasCrashed()) {
  173. await page.close();
  174. page = void 0;
  175. }
  176. await page?.mainFrame().gotoImpl(progress, "about:blank", {});
  177. await this.clock.uninstall(progress);
  178. await progress.race(this.setUserAgent(this._options.userAgent));
  179. await progress.race(this.doUpdateDefaultEmulatedMedia());
  180. await progress.race(this.doUpdateDefaultViewport());
  181. await this.setStorageState(progress, this._options.storageState, "resetForReuse");
  182. await page?.resetForReuse(progress);
  183. }
  184. _browserClosed() {
  185. for (const page of this.pages())
  186. page._didClose();
  187. this._didCloseInternal();
  188. }
  189. _didCloseInternal() {
  190. if (this._closedStatus === "closed") {
  191. return;
  192. }
  193. this._clientCertificatesProxy?.close().catch(() => {
  194. });
  195. this.tracing.abort();
  196. if (this._isPersistentContext)
  197. this.onClosePersistent();
  198. this._closePromiseFulfill(new Error("Context closed"));
  199. this.emit(BrowserContext.Events.Close);
  200. }
  201. pages() {
  202. return this.possiblyUninitializedPages().filter((page) => page.initializedOrUndefined());
  203. }
  204. async cookies(urls = []) {
  205. if (urls && !Array.isArray(urls))
  206. urls = [urls];
  207. return await this.doGetCookies(urls);
  208. }
  209. async clearCookies(options) {
  210. const currentCookies = await this.cookies();
  211. await this.doClearCookies();
  212. const matches = (cookie, prop, value) => {
  213. if (!value)
  214. return true;
  215. if (value instanceof RegExp) {
  216. value.lastIndex = 0;
  217. return value.test(cookie[prop]);
  218. }
  219. return cookie[prop] === value;
  220. };
  221. const cookiesToReadd = currentCookies.filter((cookie) => {
  222. return !matches(cookie, "name", options.name) || !matches(cookie, "domain", options.domain) || !matches(cookie, "path", options.path);
  223. });
  224. await this.addCookies(cookiesToReadd);
  225. }
  226. setHTTPCredentials(httpCredentials) {
  227. return this.doSetHTTPCredentials(httpCredentials);
  228. }
  229. getBindingClient(name) {
  230. return this._pageBindings.get(name)?.forClient;
  231. }
  232. async exposePlaywrightBindingIfNeeded() {
  233. this._playwrightBindingExposed ??= (async () => {
  234. await this.doExposePlaywrightBinding();
  235. this.bindingsInitScript = import_page2.PageBinding.createInitScript();
  236. this.initScripts.push(this.bindingsInitScript);
  237. await this.doAddInitScript(this.bindingsInitScript);
  238. await this.safeNonStallingEvaluateInAllFrames(this.bindingsInitScript.source, "main");
  239. })();
  240. return await this._playwrightBindingExposed;
  241. }
  242. needsPlaywrightBinding() {
  243. return this._playwrightBindingExposed !== void 0;
  244. }
  245. async exposeBinding(progress, name, needsHandle, playwrightBinding, forClient) {
  246. if (this._pageBindings.has(name))
  247. throw new Error(`Function "${name}" has been already registered`);
  248. for (const page of this.pages()) {
  249. if (page.getBinding(name))
  250. throw new Error(`Function "${name}" has been already registered in one of the pages`);
  251. }
  252. await progress.race(this.exposePlaywrightBindingIfNeeded());
  253. const binding = new import_page2.PageBinding(name, playwrightBinding, needsHandle);
  254. binding.forClient = forClient;
  255. this._pageBindings.set(name, binding);
  256. try {
  257. await progress.race(this.doAddInitScript(binding.initScript));
  258. await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
  259. return binding;
  260. } catch (error) {
  261. this._pageBindings.delete(name);
  262. throw error;
  263. }
  264. }
  265. async removeExposedBindings(bindings) {
  266. bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
  267. for (const binding of bindings)
  268. this._pageBindings.delete(binding.name);
  269. await this.doRemoveInitScripts(bindings.map((binding) => binding.initScript));
  270. const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
  271. `).join("");
  272. await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
  273. }
  274. async grantPermissions(permissions, origin) {
  275. let resolvedOrigin = "*";
  276. if (origin) {
  277. const url = new URL(origin);
  278. resolvedOrigin = url.origin;
  279. }
  280. const existing = new Set(this._permissions.get(resolvedOrigin) || []);
  281. permissions.forEach((p) => existing.add(p));
  282. const list = [...existing.values()];
  283. this._permissions.set(resolvedOrigin, list);
  284. await this.doGrantPermissions(resolvedOrigin, list);
  285. }
  286. async clearPermissions() {
  287. this._permissions.clear();
  288. await this.doClearPermissions();
  289. }
  290. async setExtraHTTPHeaders(progress, headers) {
  291. const oldHeaders = this._options.extraHTTPHeaders;
  292. this._options.extraHTTPHeaders = headers;
  293. try {
  294. await progress.race(this.doUpdateExtraHTTPHeaders());
  295. } catch (error) {
  296. this._options.extraHTTPHeaders = oldHeaders;
  297. this.doUpdateExtraHTTPHeaders().catch(() => {
  298. });
  299. throw error;
  300. }
  301. }
  302. async setOffline(progress, offline) {
  303. const oldOffline = this._options.offline;
  304. this._options.offline = offline;
  305. try {
  306. await progress.race(this.doUpdateOffline());
  307. } catch (error) {
  308. this._options.offline = oldOffline;
  309. this.doUpdateOffline().catch(() => {
  310. });
  311. throw error;
  312. }
  313. }
  314. async _loadDefaultContextAsIs(progress) {
  315. if (!this.possiblyUninitializedPages().length) {
  316. const waitForEvent = import_helper.helper.waitForEvent(progress, this, BrowserContext.Events.Page);
  317. await Promise.race([waitForEvent.promise, this._closePromise]);
  318. }
  319. const page = this.possiblyUninitializedPages()[0];
  320. if (!page)
  321. return;
  322. const pageOrError = await progress.race(page.waitForInitializedOrError());
  323. if (pageOrError instanceof Error)
  324. throw pageOrError;
  325. await page.mainFrame()._waitForLoadState(progress, "load");
  326. return page;
  327. }
  328. async _loadDefaultContext(progress) {
  329. const defaultPage = await this._loadDefaultContextAsIs(progress);
  330. if (!defaultPage)
  331. return;
  332. const browserName = this._browser.options.name;
  333. if (this._options.isMobile && browserName === "chromium" || this._options.locale && browserName === "webkit") {
  334. await this.newPage(progress);
  335. await defaultPage.close();
  336. }
  337. }
  338. _authenticateProxyViaHeader() {
  339. const proxy = this._options.proxy || this._browser.options.proxy || { username: void 0, password: void 0 };
  340. const { username, password } = proxy;
  341. if (username) {
  342. this._options.httpCredentials = { username, password };
  343. const token = Buffer.from(`${username}:${password}`).toString("base64");
  344. this._options.extraHTTPHeaders = network.mergeHeaders([
  345. this._options.extraHTTPHeaders,
  346. network.singleHeader("Proxy-Authorization", `Basic ${token}`)
  347. ]);
  348. }
  349. }
  350. _authenticateProxyViaCredentials() {
  351. const proxy = this._options.proxy || this._browser.options.proxy;
  352. if (!proxy)
  353. return;
  354. const { username, password } = proxy;
  355. if (username)
  356. this._options.httpCredentials = { username, password: password || "" };
  357. }
  358. async addInitScript(progress, source) {
  359. const initScript = new import_page.InitScript(source);
  360. this.initScripts.push(initScript);
  361. try {
  362. const promise = this.doAddInitScript(initScript);
  363. if (progress)
  364. await progress.race(promise);
  365. else
  366. await promise;
  367. return initScript;
  368. } catch (error) {
  369. this.removeInitScripts([initScript]).catch(() => {
  370. });
  371. throw error;
  372. }
  373. }
  374. async removeInitScripts(initScripts) {
  375. const set = new Set(initScripts);
  376. this.initScripts = this.initScripts.filter((script) => !set.has(script));
  377. await this.doRemoveInitScripts(initScripts);
  378. }
  379. async addRequestInterceptor(progress, handler) {
  380. this.requestInterceptors.push(handler);
  381. await this.doUpdateRequestInterception();
  382. }
  383. async removeRequestInterceptor(handler) {
  384. const index = this.requestInterceptors.indexOf(handler);
  385. if (index === -1)
  386. return;
  387. this.requestInterceptors.splice(index, 1);
  388. await this.notifyRoutesInFlightAboutRemovedHandler(handler);
  389. await this.doUpdateRequestInterception();
  390. }
  391. isClosingOrClosed() {
  392. return this._closedStatus !== "open";
  393. }
  394. async _deleteAllDownloads() {
  395. await Promise.all(Array.from(this._downloads).map((download) => download.artifact.deleteOnContextClose()));
  396. }
  397. async _deleteAllTempDirs() {
  398. await Promise.all(this._tempDirs.map(async (dir) => await import_fs.default.promises.unlink(dir).catch((e) => {
  399. })));
  400. }
  401. setCustomCloseHandler(handler) {
  402. this._customCloseHandler = handler;
  403. }
  404. async close(options) {
  405. if (this._closedStatus === "open") {
  406. if (options.reason)
  407. this._closeReason = options.reason;
  408. this.emit(BrowserContext.Events.BeforeClose);
  409. this._closedStatus = "closing";
  410. for (const harRecorder of this._harRecorders.values())
  411. await harRecorder.flush();
  412. await this.tracing.flush();
  413. const promises = [];
  414. for (const { context, artifact } of this._browser._idToVideo.values()) {
  415. if (context === this)
  416. promises.push(artifact.finishedPromise());
  417. }
  418. if (this._customCloseHandler) {
  419. await this._customCloseHandler();
  420. } else {
  421. await this.doClose(options.reason);
  422. }
  423. promises.push(this._deleteAllDownloads());
  424. promises.push(this._deleteAllTempDirs());
  425. await Promise.all(promises);
  426. if (!this._customCloseHandler)
  427. this._didCloseInternal();
  428. }
  429. await this._closePromise;
  430. }
  431. async newPage(progress, forStorageState) {
  432. let page;
  433. try {
  434. this._creatingStorageStatePage = !!forStorageState;
  435. page = await progress.race(this.doCreateNewPage());
  436. const pageOrError = await progress.race(page.waitForInitializedOrError());
  437. if (pageOrError instanceof import_page2.Page) {
  438. if (pageOrError.isClosed())
  439. throw new Error("Page has been closed.");
  440. return pageOrError;
  441. }
  442. throw pageOrError;
  443. } catch (error) {
  444. await page?.close({ reason: "Failed to create page" }).catch(() => {
  445. });
  446. throw error;
  447. } finally {
  448. this._creatingStorageStatePage = false;
  449. }
  450. }
  451. addVisitedOrigin(origin) {
  452. this._origins.add(origin);
  453. }
  454. async storageState(progress, indexedDB = false) {
  455. const result = {
  456. cookies: await this.cookies(),
  457. origins: []
  458. };
  459. const originsToSave = new Set(this._origins);
  460. const collectScript = `(() => {
  461. const module = {};
  462. ${rawStorageSource.source}
  463. const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"});
  464. return script.collect(${indexedDB});
  465. })()`;
  466. for (const page of this.pages()) {
  467. const origin = page.mainFrame().origin();
  468. if (!origin || !originsToSave.has(origin))
  469. continue;
  470. try {
  471. const storage = await page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, "utility");
  472. if (storage.localStorage.length || storage.indexedDB?.length)
  473. result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
  474. originsToSave.delete(origin);
  475. } catch {
  476. }
  477. }
  478. if (originsToSave.size) {
  479. const page = await this.newPage(
  480. progress,
  481. true
  482. /* forStorageState */
  483. );
  484. try {
  485. await page.addRequestInterceptor(progress, (route) => {
  486. route.fulfill({ body: "<html></html>" }).catch(() => {
  487. });
  488. }, "prepend");
  489. for (const origin of originsToSave) {
  490. const frame = page.mainFrame();
  491. await frame.gotoImpl(progress, origin, {});
  492. const storage = await progress.race(frame.evaluateExpression(collectScript, { world: "utility" }));
  493. if (storage.localStorage.length || storage.indexedDB?.length)
  494. result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
  495. }
  496. } finally {
  497. await page.close();
  498. }
  499. }
  500. return result;
  501. }
  502. isCreatingStorageStatePage() {
  503. return this._creatingStorageStatePage;
  504. }
  505. async setStorageState(progress, state, mode) {
  506. let page;
  507. let interceptor;
  508. try {
  509. if (mode !== "initial") {
  510. await progress.race(this.clearCache());
  511. await progress.race(this.doClearCookies());
  512. }
  513. if (state?.cookies)
  514. await progress.race(this.addCookies(state.cookies));
  515. const newOrigins = new Map(state?.origins?.map((p) => [p.origin, p]) || []);
  516. const allOrigins = /* @__PURE__ */ new Set([...this._origins, ...newOrigins.keys()]);
  517. if (allOrigins.size) {
  518. if (mode === "resetForReuse")
  519. page = this.pages()[0];
  520. if (!page)
  521. page = await this.newPage(
  522. progress,
  523. mode !== "resetForReuse"
  524. /* forStorageState */
  525. );
  526. interceptor = (route) => {
  527. route.fulfill({ body: "<html></html>" }).catch(() => {
  528. });
  529. };
  530. await page.addRequestInterceptor(progress, interceptor, "prepend");
  531. for (const origin of allOrigins) {
  532. const frame = page.mainFrame();
  533. await frame.gotoImpl(progress, origin, {});
  534. const restoreScript = `(() => {
  535. const module = {};
  536. ${rawStorageSource.source}
  537. const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"});
  538. return script.restore(${JSON.stringify(newOrigins.get(origin))});
  539. })()`;
  540. await progress.race(frame.evaluateExpression(restoreScript, { world: "utility" }));
  541. }
  542. }
  543. this._origins = /* @__PURE__ */ new Set([...newOrigins.keys()]);
  544. } catch (error) {
  545. (0, import_stackTrace.rewriteErrorMessage)(error, `Error setting storage state:
  546. ` + error.message);
  547. throw error;
  548. } finally {
  549. if (mode !== "resetForReuse")
  550. await page?.close();
  551. else if (interceptor)
  552. await page?.removeRequestInterceptor(interceptor);
  553. }
  554. }
  555. async extendInjectedScript(source, arg) {
  556. const installInFrame = (frame) => frame.extendInjectedScript(source, arg).catch(() => {
  557. });
  558. const installInPage = (page) => {
  559. page.on(import_page2.Page.Events.InternalFrameNavigatedToNewDocument, installInFrame);
  560. return Promise.all(page.frames().map(installInFrame));
  561. };
  562. this.on(BrowserContext.Events.Page, installInPage);
  563. return Promise.all(this.pages().map(installInPage));
  564. }
  565. async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
  566. await Promise.all(this.pages().map((page) => page.safeNonStallingEvaluateInAllFrames(expression, world, options)));
  567. }
  568. harStart(page, options) {
  569. const harId = (0, import_crypto.createGuid)();
  570. this._harRecorders.set(harId, new import_harRecorder.HarRecorder(this, page, options));
  571. return harId;
  572. }
  573. async harExport(harId) {
  574. const recorder = this._harRecorders.get(harId || "");
  575. return recorder.export();
  576. }
  577. addRouteInFlight(route) {
  578. this._routesInFlight.add(route);
  579. }
  580. removeRouteInFlight(route) {
  581. this._routesInFlight.delete(route);
  582. }
  583. async notifyRoutesInFlightAboutRemovedHandler(handler) {
  584. await Promise.all([...this._routesInFlight].map((route) => route.removeHandler(handler)));
  585. }
  586. }
  587. function validateBrowserContextOptions(options, browserOptions) {
  588. if (options.noDefaultViewport && options.deviceScaleFactor !== void 0)
  589. throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);
  590. if (options.noDefaultViewport && !!options.isMobile)
  591. throw new Error(`"isMobile" option is not supported with null "viewport"`);
  592. if (options.acceptDownloads === void 0 && browserOptions.name !== "electron")
  593. options.acceptDownloads = "accept";
  594. else if (options.acceptDownloads === void 0 && browserOptions.name === "electron")
  595. options.acceptDownloads = "internal-browser-default";
  596. if (!options.viewport && !options.noDefaultViewport)
  597. options.viewport = { width: 1280, height: 720 };
  598. if (options.recordVideo) {
  599. if (!options.recordVideo.size) {
  600. if (options.noDefaultViewport) {
  601. options.recordVideo.size = { width: 800, height: 600 };
  602. } else {
  603. const size = options.viewport;
  604. const scale = Math.min(1, 800 / Math.max(size.width, size.height));
  605. options.recordVideo.size = {
  606. width: Math.floor(size.width * scale),
  607. height: Math.floor(size.height * scale)
  608. };
  609. }
  610. }
  611. options.recordVideo.size.width &= ~1;
  612. options.recordVideo.size.height &= ~1;
  613. }
  614. if (options.proxy)
  615. options.proxy = normalizeProxySettings(options.proxy);
  616. verifyGeolocation(options.geolocation);
  617. }
  618. function verifyGeolocation(geolocation) {
  619. if (!geolocation)
  620. return;
  621. geolocation.accuracy = geolocation.accuracy || 0;
  622. const { longitude, latitude, accuracy } = geolocation;
  623. if (longitude < -180 || longitude > 180)
  624. throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);
  625. if (latitude < -90 || latitude > 90)
  626. throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);
  627. if (accuracy < 0)
  628. throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);
  629. }
  630. function verifyClientCertificates(clientCertificates) {
  631. if (!clientCertificates)
  632. return;
  633. for (const cert of clientCertificates) {
  634. if (!cert.origin)
  635. throw new Error(`clientCertificates.origin is required`);
  636. if (!cert.cert && !cert.key && !cert.passphrase && !cert.pfx)
  637. throw new Error("None of cert, key, passphrase or pfx is specified");
  638. if (cert.cert && !cert.key)
  639. throw new Error("cert is specified without key");
  640. if (!cert.cert && cert.key)
  641. throw new Error("key is specified without cert");
  642. if (cert.pfx && (cert.cert || cert.key))
  643. throw new Error("pfx is specified together with cert, key or passphrase");
  644. }
  645. }
  646. function normalizeProxySettings(proxy) {
  647. let { server, bypass } = proxy;
  648. let url;
  649. try {
  650. url = new URL(server);
  651. if (!url.host || !url.protocol)
  652. url = new URL("http://" + server);
  653. } catch (e) {
  654. url = new URL("http://" + server);
  655. }
  656. if (url.protocol === "socks4:" && (proxy.username || proxy.password))
  657. throw new Error(`Socks4 proxy protocol does not support authentication`);
  658. if (url.protocol === "socks5:" && (proxy.username || proxy.password))
  659. throw new Error(`Browser does not support socks5 proxy authentication`);
  660. server = url.protocol + "//" + url.host;
  661. if (bypass)
  662. bypass = bypass.split(",").map((t) => t.trim()).join(",");
  663. return { ...proxy, server, bypass };
  664. }
  665. const paramsThatAllowContextReuse = [
  666. "colorScheme",
  667. "forcedColors",
  668. "reducedMotion",
  669. "contrast",
  670. "screen",
  671. "userAgent",
  672. "viewport",
  673. "testIdAttributeName"
  674. ];
  675. const defaultNewContextParamValues = {
  676. noDefaultViewport: false,
  677. ignoreHTTPSErrors: false,
  678. javaScriptEnabled: true,
  679. bypassCSP: false,
  680. offline: false,
  681. isMobile: false,
  682. hasTouch: false,
  683. acceptDownloads: "accept",
  684. strictSelectors: false,
  685. serviceWorkers: "allow",
  686. locale: "en-US"
  687. };
  688. // Annotate the CommonJS export names for ESM import in node:
  689. 0 && (module.exports = {
  690. BrowserContext,
  691. normalizeProxySettings,
  692. validateBrowserContextOptions,
  693. verifyClientCertificates,
  694. verifyGeolocation
  695. });