2020-06-25 16:05:36 -07:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
* Modifications copyright (c) Microsoft Corporation.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2020-12-26 17:05:57 -08:00
|
|
|
import { Page, BindingCall } from './page';
|
2021-08-16 12:49:10 -07:00
|
|
|
import { Frame } from './frame';
|
2020-06-25 16:05:36 -07:00
|
|
|
import * as network from './network';
|
2022-09-20 18:41:51 -07:00
|
|
|
import type * as channels from '@protocol/channels';
|
2021-02-11 06:36:15 -08:00
|
|
|
import fs from 'fs';
|
2023-09-15 10:26:20 -07:00
|
|
|
import path from 'path';
|
2020-06-25 16:05:36 -07:00
|
|
|
import { ChannelOwner } from './channelOwner';
|
2022-01-12 19:52:40 -08:00
|
|
|
import { evaluationScript } from './clientHelper';
|
2020-06-25 16:05:36 -07:00
|
|
|
import { Browser } from './browser';
|
2021-04-02 09:47:14 +08:00
|
|
|
import { Worker } from './worker';
|
2020-07-29 17:26:59 -07:00
|
|
|
import { Events } from './events';
|
2022-04-07 13:36:13 -08:00
|
|
|
import { TimeoutSettings } from '../common/timeoutSettings';
|
2020-07-13 16:03:24 -07:00
|
|
|
import { Waiter } from './waiter';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { URLMatch, Headers, WaitForEventOptions, BrowserContextOptions, StorageState, LaunchOptions } from './types';
|
2023-05-17 16:27:32 -07:00
|
|
|
import { headersObjectToArray, isRegExp, isString, urlMatchesEqual } from '../utils';
|
2022-04-07 19:18:22 -08:00
|
|
|
import { mkdirIfNeeded } from '../utils/fileUtils';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type * as api from '../../types/types';
|
|
|
|
import type * as structs from '../../types/structs';
|
2021-04-02 09:47:14 +08:00
|
|
|
import { CDPSession } from './cdpSession';
|
2021-04-24 20:39:48 -07:00
|
|
|
import { Tracing } from './tracing';
|
2021-08-09 18:09:11 -07:00
|
|
|
import type { BrowserType } from './browserType';
|
2021-08-26 11:26:08 -07:00
|
|
|
import { Artifact } from './artifact';
|
2021-11-05 16:27:49 +01:00
|
|
|
import { APIRequestContext } from './fetch';
|
2022-03-24 07:33:51 -07:00
|
|
|
import { rewriteErrorMessage } from '../utils/stackTrace';
|
2023-02-18 11:41:24 -08:00
|
|
|
import { HarRouter } from './harRouter';
|
2023-05-04 15:11:46 -07:00
|
|
|
import { ConsoleMessage } from './consoleMessage';
|
|
|
|
import { Dialog } from './dialog';
|
2023-09-06 12:40:53 -07:00
|
|
|
import { WebError } from './webError';
|
2023-10-17 21:34:02 -07:00
|
|
|
import { TargetClosedError, parseError } from './errors';
|
2020-06-25 16:05:36 -07:00
|
|
|
|
2021-11-17 15:26:01 -08:00
|
|
|
export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel> implements api.BrowserContext {
|
2020-06-25 16:05:36 -07:00
|
|
|
_pages = new Set<Page>();
|
2023-02-18 11:41:24 -08:00
|
|
|
private _routes: network.RouteHandler[] = [];
|
2020-09-14 16:50:47 +02:00
|
|
|
readonly _browser: Browser | null = null;
|
2023-03-16 07:03:33 -07:00
|
|
|
_browserType: BrowserType | undefined;
|
2020-12-26 17:05:57 -08:00
|
|
|
readonly _bindings = new Map<string, (source: structs.BindingSource, ...args: any[]) => any>();
|
2020-06-26 21:22:03 -07:00
|
|
|
_timeoutSettings = new TimeoutSettings();
|
2020-06-29 16:37:38 -07:00
|
|
|
_ownerPage: Page | undefined;
|
2020-07-09 15:33:01 -07:00
|
|
|
private _closedPromise: Promise<void>;
|
2021-08-20 21:32:21 +02:00
|
|
|
_options: channels.BrowserNewContextParams = { };
|
2020-06-25 16:05:36 -07:00
|
|
|
|
2021-11-05 16:27:49 +01:00
|
|
|
readonly request: APIRequestContext;
|
2021-05-12 12:21:54 -07:00
|
|
|
readonly tracing: Tracing;
|
2021-04-02 09:47:14 +08:00
|
|
|
readonly _backgroundPages = new Set<Page>();
|
|
|
|
readonly _serviceWorkers = new Set<Worker>();
|
|
|
|
readonly _isChromium: boolean;
|
2022-06-28 15:09:36 -07:00
|
|
|
private _harRecorders = new Map<string, { path: string, content: 'embed' | 'attach' | 'omit' | undefined }>();
|
2023-03-02 13:46:54 -08:00
|
|
|
private _closeWasCalled = false;
|
2023-10-17 15:35:41 -07:00
|
|
|
private _closeReason: string | undefined;
|
2021-04-02 09:47:14 +08:00
|
|
|
|
2020-08-24 17:05:16 -07:00
|
|
|
static from(context: channels.BrowserContextChannel): BrowserContext {
|
2020-07-01 18:36:09 -07:00
|
|
|
return (context as any)._object;
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-08-24 17:05:16 -07:00
|
|
|
static fromNullable(context: channels.BrowserContextChannel | null): BrowserContext | null {
|
2020-06-25 16:05:36 -07:00
|
|
|
return context ? BrowserContext.from(context) : null;
|
|
|
|
}
|
|
|
|
|
2021-01-13 12:08:14 -08:00
|
|
|
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserContextInitializer) {
|
2023-04-28 08:57:43 -07:00
|
|
|
super(parent, type, guid, initializer);
|
2020-07-13 21:46:59 -07:00
|
|
|
if (parent instanceof Browser)
|
2020-07-13 15:26:09 -07:00
|
|
|
this._browser = parent;
|
2023-03-16 07:03:33 -07:00
|
|
|
this._browser?._contexts.add(this);
|
2021-04-02 09:47:14 +08:00
|
|
|
this._isChromium = this._browser?._name === 'chromium';
|
2022-01-22 11:25:13 -08:00
|
|
|
this.tracing = Tracing.from(initializer.tracing);
|
2022-07-15 07:56:47 -08:00
|
|
|
this.request = APIRequestContext.from(initializer.requestContext);
|
2020-07-13 15:26:09 -07:00
|
|
|
|
2021-09-27 18:58:08 +02:00
|
|
|
this._channel.on('bindingCall', ({ binding }) => this._onBinding(BindingCall.from(binding)));
|
2020-06-30 10:55:11 -07:00
|
|
|
this._channel.on('close', () => this._onClose());
|
2021-09-27 18:58:08 +02:00
|
|
|
this._channel.on('page', ({ page }) => this._onPage(Page.from(page)));
|
2022-08-25 11:58:41 -07:00
|
|
|
this._channel.on('route', ({ route }) => this._onRoute(network.Route.from(route)));
|
2021-04-02 09:47:14 +08:00
|
|
|
this._channel.on('backgroundPage', ({ page }) => {
|
|
|
|
const backgroundPage = Page.from(page);
|
|
|
|
this._backgroundPages.add(backgroundPage);
|
|
|
|
this.emit(Events.BrowserContext.BackgroundPage, backgroundPage);
|
|
|
|
});
|
2021-09-27 18:58:08 +02:00
|
|
|
this._channel.on('serviceWorker', ({ worker }) => {
|
2021-04-02 09:47:14 +08:00
|
|
|
const serviceWorker = Worker.from(worker);
|
|
|
|
serviceWorker._context = this;
|
|
|
|
this._serviceWorkers.add(serviceWorker);
|
|
|
|
this.emit(Events.BrowserContext.ServiceWorker, serviceWorker);
|
|
|
|
});
|
2023-09-21 16:16:43 -07:00
|
|
|
this._channel.on('console', event => {
|
|
|
|
const consoleMessage = new ConsoleMessage(event);
|
2023-05-04 15:11:46 -07:00
|
|
|
this.emit(Events.BrowserContext.Console, consoleMessage);
|
|
|
|
const page = consoleMessage.page();
|
|
|
|
if (page)
|
|
|
|
page.emit(Events.Page.Console, consoleMessage);
|
|
|
|
});
|
2023-08-17 09:10:03 -07:00
|
|
|
this._channel.on('pageError', ({ error, page }) => {
|
|
|
|
const pageObject = Page.from(page);
|
|
|
|
const parsedError = parseError(error);
|
2023-09-06 12:40:53 -07:00
|
|
|
this.emit(Events.BrowserContext.WebError, new WebError(pageObject, parsedError));
|
2023-08-17 09:10:03 -07:00
|
|
|
if (pageObject)
|
|
|
|
pageObject.emit(Events.Page.PageError, parsedError);
|
|
|
|
});
|
2023-05-04 15:11:46 -07:00
|
|
|
this._channel.on('dialog', ({ dialog }) => {
|
|
|
|
const dialogObject = Dialog.from(dialog);
|
|
|
|
let hasListeners = this.emit(Events.BrowserContext.Dialog, dialogObject);
|
|
|
|
const page = dialogObject.page();
|
|
|
|
if (page)
|
|
|
|
hasListeners = page.emit(Events.Page.Dialog, dialogObject) || hasListeners;
|
|
|
|
if (!hasListeners) {
|
2023-05-05 11:12:33 -07:00
|
|
|
// Although we do similar handling on the server side, we still need this logic
|
|
|
|
// on the client side due to a possible race condition between two async calls:
|
|
|
|
// a) removing "dialog" listener subscription (client->server)
|
|
|
|
// b) actual "dialog" event (server->client)
|
2023-05-04 15:11:46 -07:00
|
|
|
if (dialogObject.type() === 'beforeunload')
|
|
|
|
dialog.accept({}).catch(() => {});
|
|
|
|
else
|
|
|
|
dialog.dismiss().catch(() => {});
|
|
|
|
}
|
|
|
|
});
|
2021-05-13 10:29:14 -07:00
|
|
|
this._channel.on('request', ({ request, page }) => this._onRequest(network.Request.from(request), Page.fromNullable(page)));
|
|
|
|
this._channel.on('requestFailed', ({ request, failureText, responseEndTiming, page }) => this._onRequestFailed(network.Request.from(request), responseEndTiming, failureText, Page.fromNullable(page)));
|
2021-08-30 20:43:40 -07:00
|
|
|
this._channel.on('requestFinished', params => this._onRequestFinished(params));
|
2021-05-13 10:29:14 -07:00
|
|
|
this._channel.on('response', ({ response, page }) => this._onResponse(network.Response.from(response), Page.fromNullable(page)));
|
2020-07-09 15:33:01 -07:00
|
|
|
this._closedPromise = new Promise(f => this.once(Events.BrowserContext.Close, f));
|
2022-11-09 21:10:57 -08:00
|
|
|
|
|
|
|
this._setEventToSubscriptionMapping(new Map<string, channels.BrowserContextUpdateSubscriptionParams['event']>([
|
2023-05-05 11:12:33 -07:00
|
|
|
[Events.BrowserContext.Console, 'console'],
|
|
|
|
[Events.BrowserContext.Dialog, 'dialog'],
|
2022-11-09 21:10:57 -08:00
|
|
|
[Events.BrowserContext.Request, 'request'],
|
|
|
|
[Events.BrowserContext.Response, 'response'],
|
|
|
|
[Events.BrowserContext.RequestFinished, 'requestFinished'],
|
|
|
|
[Events.BrowserContext.RequestFailed, 'requestFailed'],
|
|
|
|
]));
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2023-03-16 07:03:33 -07:00
|
|
|
_setOptions(contextOptions: channels.BrowserNewContextParams, browserOptions: LaunchOptions) {
|
|
|
|
this._options = contextOptions;
|
2022-06-28 15:09:36 -07:00
|
|
|
if (this._options.recordHar)
|
|
|
|
this._harRecorders.set('', { path: this._options.recordHar.path, content: this._options.recordHar.content });
|
2023-03-16 07:03:33 -07:00
|
|
|
this.tracing._tracesDir = browserOptions.tracesDir;
|
2021-08-09 18:09:11 -07:00
|
|
|
}
|
|
|
|
|
2020-06-26 12:28:27 -07:00
|
|
|
private _onPage(page: Page): void {
|
|
|
|
this._pages.add(page);
|
|
|
|
this.emit(Events.BrowserContext.Page, page);
|
2021-04-02 11:15:07 -07:00
|
|
|
if (page._opener && !page._opener.isClosed())
|
|
|
|
page._opener.emit(Events.Page.Popup, page);
|
2020-06-26 12:28:27 -07:00
|
|
|
}
|
2020-06-26 11:51:47 -07:00
|
|
|
|
2021-05-13 10:29:14 -07:00
|
|
|
private _onRequest(request: network.Request, page: Page | null) {
|
|
|
|
this.emit(Events.BrowserContext.Request, request);
|
|
|
|
if (page)
|
|
|
|
page.emit(Events.Page.Request, request);
|
|
|
|
}
|
|
|
|
|
|
|
|
private _onResponse(response: network.Response, page: Page | null) {
|
|
|
|
this.emit(Events.BrowserContext.Response, response);
|
|
|
|
if (page)
|
|
|
|
page.emit(Events.Page.Response, response);
|
|
|
|
}
|
|
|
|
|
|
|
|
private _onRequestFailed(request: network.Request, responseEndTiming: number, failureText: string | undefined, page: Page | null) {
|
|
|
|
request._failureText = failureText || null;
|
2022-09-26 17:12:47 -07:00
|
|
|
request._setResponseEndTiming(responseEndTiming);
|
2021-05-13 10:29:14 -07:00
|
|
|
this.emit(Events.BrowserContext.RequestFailed, request);
|
|
|
|
if (page)
|
|
|
|
page.emit(Events.Page.RequestFailed, request);
|
|
|
|
}
|
|
|
|
|
2021-08-30 20:43:40 -07:00
|
|
|
private _onRequestFinished(params: channels.BrowserContextRequestFinishedEvent) {
|
2021-09-02 10:39:57 -07:00
|
|
|
const { responseEndTiming } = params;
|
2021-08-30 20:43:40 -07:00
|
|
|
const request = network.Request.from(params.request);
|
|
|
|
const response = network.Response.fromNullable(params.response);
|
|
|
|
const page = Page.fromNullable(params.page);
|
2022-09-26 17:12:47 -07:00
|
|
|
request._setResponseEndTiming(responseEndTiming);
|
2021-05-13 10:29:14 -07:00
|
|
|
this.emit(Events.BrowserContext.RequestFinished, request);
|
|
|
|
if (page)
|
|
|
|
page.emit(Events.Page.RequestFinished, request);
|
2021-08-30 20:43:40 -07:00
|
|
|
if (response)
|
2023-03-06 08:50:03 -08:00
|
|
|
response._finishedPromise.resolve(null);
|
2021-05-13 10:29:14 -07:00
|
|
|
}
|
|
|
|
|
2022-08-25 11:58:41 -07:00
|
|
|
async _onRoute(route: network.Route) {
|
2023-08-21 16:48:51 -07:00
|
|
|
route._context = this;
|
2023-02-18 11:41:24 -08:00
|
|
|
const routeHandlers = this._routes.slice();
|
|
|
|
for (const routeHandler of routeHandlers) {
|
|
|
|
if (!routeHandler.matches(route.request().url()))
|
|
|
|
continue;
|
|
|
|
if (routeHandler.willExpire())
|
|
|
|
this._routes.splice(this._routes.indexOf(routeHandler), 1);
|
|
|
|
const handled = await routeHandler.handle(route);
|
|
|
|
if (!this._routes.length)
|
|
|
|
this._wrapApiCall(() => this._updateInterceptionPatterns(), true).catch(() => {});
|
|
|
|
if (handled)
|
|
|
|
return;
|
|
|
|
}
|
2022-06-13 16:56:16 -08:00
|
|
|
await route._innerContinue(true);
|
2020-06-26 11:51:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async _onBinding(bindingCall: BindingCall) {
|
2020-06-26 12:28:27 -07:00
|
|
|
const func = this._bindings.get(bindingCall._initializer.name);
|
2020-06-26 11:51:47 -07:00
|
|
|
if (!func)
|
|
|
|
return;
|
2021-03-22 09:59:39 -07:00
|
|
|
await bindingCall.call(func);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2023-06-07 12:30:10 -07:00
|
|
|
setDefaultNavigationTimeout(timeout: number | undefined) {
|
2020-07-13 16:03:24 -07:00
|
|
|
this._timeoutSettings.setDefaultNavigationTimeout(timeout);
|
2021-12-16 17:17:24 -08:00
|
|
|
this._wrapApiCall(async () => {
|
2022-07-11 12:10:08 -08:00
|
|
|
this._channel.setDefaultNavigationTimeoutNoReply({ timeout }).catch(() => {});
|
2021-12-16 17:17:24 -08:00
|
|
|
}, true);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2023-06-07 12:30:10 -07:00
|
|
|
setDefaultTimeout(timeout: number | undefined) {
|
2020-06-26 21:22:03 -07:00
|
|
|
this._timeoutSettings.setDefaultTimeout(timeout);
|
2021-12-16 17:17:24 -08:00
|
|
|
this._wrapApiCall(async () => {
|
2022-07-11 12:10:08 -08:00
|
|
|
this._channel.setDefaultTimeoutNoReply({ timeout }).catch(() => {});
|
2021-12-16 17:17:24 -08:00
|
|
|
}, true);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-09-14 16:50:47 +02:00
|
|
|
browser(): Browser | null {
|
|
|
|
return this._browser;
|
|
|
|
}
|
|
|
|
|
2020-06-25 16:05:36 -07:00
|
|
|
pages(): Page[] {
|
|
|
|
return [...this._pages];
|
|
|
|
}
|
|
|
|
|
|
|
|
async newPage(): Promise<Page> {
|
2021-11-19 16:28:11 -08:00
|
|
|
if (this._ownerPage)
|
|
|
|
throw new Error('Please use browser.newContext()');
|
|
|
|
return Page.from((await this._channel.newPage()).page);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async cookies(urls?: string | string[]): Promise<network.NetworkCookie[]> {
|
|
|
|
if (!urls)
|
|
|
|
urls = [];
|
|
|
|
if (urls && typeof urls === 'string')
|
2022-08-18 20:12:33 +02:00
|
|
|
urls = [urls];
|
2021-11-19 16:28:11 -08:00
|
|
|
return (await this._channel.cookies({ urls: urls as string[] })).cookies;
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async addCookies(cookies: network.SetNetworkCookieParam[]): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.addCookies({ cookies });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async clearCookies(): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.clearCookies();
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async grantPermissions(permissions: string[], options?: { origin?: string }): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.grantPermissions({ permissions, ...options });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async clearPermissions(): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.clearPermissions();
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-07-29 17:26:59 -07:00
|
|
|
async setGeolocation(geolocation: { longitude: number, latitude: number, accuracy?: number } | null): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.setGeolocation({ geolocation: geolocation || undefined });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-07-29 17:26:59 -07:00
|
|
|
async setExtraHTTPHeaders(headers: Headers): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
network.validateHeaders(headers);
|
|
|
|
await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async setOffline(offline: boolean): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.setOffline({ offline });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-07-29 17:26:59 -07:00
|
|
|
async setHTTPCredentials(httpCredentials: { username: string, password: string } | null): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.setHTTPCredentials({ httpCredentials: httpCredentials || undefined });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
const source = await evaluationScript(script, arg);
|
|
|
|
await this._channel.addInitScript({ source });
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2021-01-04 13:50:29 -08:00
|
|
|
async exposeBinding(name: string, callback: (source: structs.BindingSource, ...args: any[]) => any, options: { handle?: boolean } = {}): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.exposeBinding({ name, needsHandle: options.handle });
|
|
|
|
this._bindings.set(name, callback);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2021-01-04 13:50:29 -08:00
|
|
|
async exposeFunction(name: string, callback: Function): Promise<void> {
|
2021-11-19 16:28:11 -08:00
|
|
|
await this._channel.exposeBinding({ name });
|
|
|
|
const binding = (source: structs.BindingSource, ...args: any[]) => callback(...args);
|
|
|
|
this._bindings.set(name, binding);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2021-08-24 20:45:50 +02:00
|
|
|
async route(url: URLMatch, handler: network.RouteHandlerCallback, options: { times?: number } = {}): Promise<void> {
|
2023-02-18 11:41:24 -08:00
|
|
|
this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times));
|
|
|
|
await this._updateInterceptionPatterns();
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2023-03-17 11:49:45 -07:00
|
|
|
async _recordIntoHAR(har: string, page: Page | null, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full'} = {}): Promise<void> {
|
2022-06-28 15:09:36 -07:00
|
|
|
const { harId } = await this._channel.harStart({
|
|
|
|
page: page?._channel,
|
|
|
|
options: prepareRecordHarOptions({
|
|
|
|
path: har,
|
2023-03-17 11:49:45 -07:00
|
|
|
content: options.updateContent ?? 'attach',
|
|
|
|
mode: options.updateMode ?? 'minimal',
|
2022-06-28 15:09:36 -07:00
|
|
|
urlFilter: options.url
|
|
|
|
})!
|
|
|
|
});
|
2023-03-17 11:49:45 -07:00
|
|
|
this._harRecorders.set(harId, { path: har, content: options.updateContent ?? 'attach' });
|
2022-06-28 15:09:36 -07:00
|
|
|
}
|
|
|
|
|
2023-03-17 11:49:45 -07:00
|
|
|
async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full' } = {}): Promise<void> {
|
2022-06-28 15:09:36 -07:00
|
|
|
if (options.update) {
|
|
|
|
await this._recordIntoHAR(har, null, options);
|
|
|
|
return;
|
|
|
|
}
|
2023-02-18 11:41:24 -08:00
|
|
|
const harRouter = await HarRouter.create(this._connection.localUtils(), har, options.notFound || 'abort', { urlMatch: options.url });
|
|
|
|
harRouter.addContextRoute(this);
|
2022-06-21 22:12:37 -07:00
|
|
|
}
|
|
|
|
|
2021-08-24 20:45:50 +02:00
|
|
|
async unroute(url: URLMatch, handler?: network.RouteHandlerCallback): Promise<void> {
|
2023-05-17 16:27:32 -07:00
|
|
|
this._routes = this._routes.filter(route => !urlMatchesEqual(route.url, url) || (handler && route.handler !== handler));
|
2023-02-18 11:41:24 -08:00
|
|
|
await this._updateInterceptionPatterns();
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _updateInterceptionPatterns() {
|
|
|
|
const patterns = network.RouteHandler.prepareInterceptionPatterns(this._routes);
|
|
|
|
await this._channel.setNetworkInterceptionPatterns({ patterns });
|
2021-10-21 10:23:49 -08:00
|
|
|
}
|
2020-06-25 16:05:36 -07:00
|
|
|
|
2023-10-17 15:35:41 -07:00
|
|
|
_effectiveCloseReason(): string | undefined {
|
|
|
|
return this._closeReason || this._browser?._closeReason;
|
|
|
|
}
|
|
|
|
|
2020-07-29 17:26:59 -07:00
|
|
|
async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {
|
2021-11-19 16:28:11 -08:00
|
|
|
return this._wrapApiCall(async () => {
|
2021-06-28 13:27:38 -07:00
|
|
|
const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);
|
|
|
|
const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;
|
2021-12-13 13:32:53 -08:00
|
|
|
const waiter = Waiter.createForEvent(this, event);
|
2021-12-06 15:42:57 -08:00
|
|
|
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
|
2021-06-28 13:27:38 -07:00
|
|
|
if (event !== Events.BrowserContext.Close)
|
2023-10-17 15:35:41 -07:00
|
|
|
waiter.rejectOnEvent(this, Events.BrowserContext.Close, () => new TargetClosedError(this._effectiveCloseReason()));
|
2021-06-28 13:27:38 -07:00
|
|
|
const result = await waiter.waitForEvent(this, event, predicate as any);
|
|
|
|
waiter.dispose();
|
|
|
|
return result;
|
|
|
|
});
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
|
|
|
|
2020-12-14 16:03:52 -08:00
|
|
|
async storageState(options: { path?: string } = {}): Promise<StorageState> {
|
2021-11-19 16:28:11 -08:00
|
|
|
const state = await this._channel.storageState();
|
|
|
|
if (options.path) {
|
|
|
|
await mkdirIfNeeded(options.path);
|
|
|
|
await fs.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');
|
|
|
|
}
|
|
|
|
return state;
|
2020-11-13 14:24:53 -08:00
|
|
|
}
|
|
|
|
|
2021-04-02 09:47:14 +08:00
|
|
|
backgroundPages(): Page[] {
|
|
|
|
return [...this._backgroundPages];
|
|
|
|
}
|
|
|
|
|
|
|
|
serviceWorkers(): Worker[] {
|
|
|
|
return [...this._serviceWorkers];
|
|
|
|
}
|
|
|
|
|
2021-08-16 12:49:10 -07:00
|
|
|
async newCDPSession(page: Page | Frame): Promise<api.CDPSession> {
|
|
|
|
// channelOwner.ts's validation messages don't handle the pseudo-union type, so we're explicit here
|
|
|
|
if (!(page instanceof Page) && !(page instanceof Frame))
|
|
|
|
throw new Error('page: expected Page or Frame');
|
2021-11-19 16:28:11 -08:00
|
|
|
const result = await this._channel.newCDPSession(page instanceof Page ? { page: page._channel } : { frame: page._channel });
|
|
|
|
return CDPSession.from(result.session);
|
2021-04-02 09:47:14 +08:00
|
|
|
}
|
|
|
|
|
2021-03-22 09:59:39 -07:00
|
|
|
_onClose() {
|
2020-06-26 17:24:21 -07:00
|
|
|
if (this._browser)
|
|
|
|
this._browser._contexts.delete(this);
|
2021-08-09 18:09:11 -07:00
|
|
|
this._browserType?._contexts?.delete(this);
|
2021-01-22 09:58:31 -08:00
|
|
|
this.emit(Events.BrowserContext.Close, this);
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
2020-06-30 10:55:11 -07:00
|
|
|
|
2023-10-16 20:32:13 -07:00
|
|
|
async close(options: { reason?: string } = {}): Promise<void> {
|
2023-03-02 13:46:54 -08:00
|
|
|
if (this._closeWasCalled)
|
|
|
|
return;
|
2023-10-17 15:35:41 -07:00
|
|
|
this._closeReason = options.reason;
|
2023-03-02 13:46:54 -08:00
|
|
|
this._closeWasCalled = true;
|
|
|
|
await this._wrapApiCall(async () => {
|
2023-03-16 07:03:33 -07:00
|
|
|
await this._browserType?._willCloseContext(this);
|
2023-03-02 13:46:54 -08:00
|
|
|
for (const [harId, harParams] of this._harRecorders) {
|
|
|
|
const har = await this._channel.harExport({ harId });
|
|
|
|
const artifact = Artifact.from(har.artifact);
|
|
|
|
// Server side will compress artifact if content is attach or if file is .zip.
|
|
|
|
const isCompressed = harParams.content === 'attach' || harParams.path.endsWith('.zip');
|
|
|
|
const needCompressed = harParams.path.endsWith('.zip');
|
|
|
|
if (isCompressed && !needCompressed) {
|
|
|
|
await artifact.saveAs(harParams.path + '.tmp');
|
|
|
|
await this._connection.localUtils()._channel.harUnzip({ zipFile: harParams.path + '.tmp', harFile: harParams.path });
|
|
|
|
} else {
|
|
|
|
await artifact.saveAs(harParams.path);
|
2021-08-25 13:32:56 -07:00
|
|
|
}
|
2023-03-02 13:46:54 -08:00
|
|
|
await artifact.delete();
|
|
|
|
}
|
|
|
|
}, true);
|
2023-10-16 20:32:13 -07:00
|
|
|
await this._channel.close(options);
|
2023-03-02 13:46:54 -08:00
|
|
|
await this._closedPromise;
|
2020-06-30 10:55:11 -07:00
|
|
|
}
|
2021-01-25 14:49:26 -08:00
|
|
|
|
2021-01-25 19:01:04 -08:00
|
|
|
async _enableRecorder(params: {
|
|
|
|
language: string,
|
|
|
|
launchOptions?: LaunchOptions,
|
|
|
|
contextOptions?: BrowserContextOptions,
|
|
|
|
device?: string,
|
|
|
|
saveStorage?: string,
|
2022-08-05 19:34:57 -07:00
|
|
|
mode?: 'recording' | 'inspecting',
|
2023-04-29 12:04:33 -07:00
|
|
|
testIdAttributeName?: string,
|
2022-08-09 00:13:38 +02:00
|
|
|
outputFile?: string,
|
|
|
|
handleSIGINT?: boolean,
|
2021-01-25 19:01:04 -08:00
|
|
|
}) {
|
|
|
|
await this._channel.recorderSupplementEnable(params);
|
2021-01-25 14:49:26 -08:00
|
|
|
}
|
2020-06-25 16:05:36 -07:00
|
|
|
}
|
2020-11-02 19:42:05 -08:00
|
|
|
|
2022-03-24 07:33:51 -07:00
|
|
|
async function prepareStorageState(options: BrowserContextOptions): Promise<channels.BrowserNewContextParams['storageState']> {
|
|
|
|
if (typeof options.storageState !== 'string')
|
|
|
|
return options.storageState;
|
|
|
|
try {
|
|
|
|
return JSON.parse(await fs.promises.readFile(options.storageState, 'utf8'));
|
|
|
|
} catch (e) {
|
|
|
|
rewriteErrorMessage(e, `Error reading storage state from ${options.storageState}:\n` + e.message);
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-07 18:09:47 -07:00
|
|
|
function prepareRecordHarOptions(options: BrowserContextOptions['recordHar']): channels.RecordHarOptions | undefined {
|
|
|
|
if (!options)
|
|
|
|
return;
|
|
|
|
return {
|
|
|
|
path: options.path,
|
2022-06-16 17:27:25 -08:00
|
|
|
content: options.content || (options.omitContent ? 'omit' : undefined),
|
2022-06-07 18:09:47 -07:00
|
|
|
urlGlob: isString(options.urlFilter) ? options.urlFilter : undefined,
|
|
|
|
urlRegexSource: isRegExp(options.urlFilter) ? options.urlFilter.source : undefined,
|
|
|
|
urlRegexFlags: isRegExp(options.urlFilter) ? options.urlFilter.flags : undefined,
|
2022-06-22 14:44:12 -07:00
|
|
|
mode: options.mode
|
2022-06-07 18:09:47 -07:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-02-11 17:46:54 -08:00
|
|
|
export async function prepareBrowserContextParams(options: BrowserContextOptions): Promise<channels.BrowserNewContextParams> {
|
2020-11-02 19:42:05 -08:00
|
|
|
if (options.videoSize && !options.videosPath)
|
|
|
|
throw new Error(`"videoSize" option requires "videosPath" to be specified`);
|
|
|
|
if (options.extraHTTPHeaders)
|
|
|
|
network.validateHeaders(options.extraHTTPHeaders);
|
2021-02-11 17:46:54 -08:00
|
|
|
const contextParams: channels.BrowserNewContextParams = {
|
2020-11-02 19:42:05 -08:00
|
|
|
...options,
|
|
|
|
viewport: options.viewport === null ? undefined : options.viewport,
|
|
|
|
noDefaultViewport: options.viewport === null,
|
|
|
|
extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
|
2022-03-24 07:33:51 -07:00
|
|
|
storageState: await prepareStorageState(options),
|
2022-06-08 18:27:51 -04:00
|
|
|
serviceWorkers: options.serviceWorkers,
|
2022-06-07 18:09:47 -07:00
|
|
|
recordHar: prepareRecordHarOptions(options.recordHar),
|
2022-10-31 09:09:52 -07:00
|
|
|
colorScheme: options.colorScheme === null ? 'no-override' : options.colorScheme,
|
|
|
|
reducedMotion: options.reducedMotion === null ? 'no-override' : options.reducedMotion,
|
|
|
|
forcedColors: options.forcedColors === null ? 'no-override' : options.forcedColors,
|
2023-08-17 10:57:28 +02:00
|
|
|
acceptDownloads: toAcceptDownloadsProtocol(options.acceptDownloads),
|
2020-11-02 19:42:05 -08:00
|
|
|
};
|
2021-02-11 17:46:54 -08:00
|
|
|
if (!contextParams.recordVideo && options.videosPath) {
|
|
|
|
contextParams.recordVideo = {
|
2020-11-02 19:42:05 -08:00
|
|
|
dir: options.videosPath,
|
|
|
|
size: options.videoSize
|
|
|
|
};
|
|
|
|
}
|
2023-09-15 10:26:20 -07:00
|
|
|
if (contextParams.recordVideo && contextParams.recordVideo.dir)
|
|
|
|
contextParams.recordVideo.dir = path.resolve(process.cwd(), contextParams.recordVideo.dir);
|
2021-02-11 17:46:54 -08:00
|
|
|
return contextParams;
|
2020-11-02 19:42:05 -08:00
|
|
|
}
|
2023-08-17 10:57:28 +02:00
|
|
|
|
|
|
|
function toAcceptDownloadsProtocol(acceptDownloads?: boolean) {
|
|
|
|
if (acceptDownloads === undefined)
|
|
|
|
return undefined;
|
|
|
|
if (acceptDownloads === true)
|
|
|
|
return 'accept';
|
|
|
|
return 'deny';
|
|
|
|
}
|