chore(context): unify browser context id handling (#3629)

This commit is contained in:
Yury Semikhatsky 2020-08-25 16:33:16 -07:00 committed by GitHub
parent a2a96198e6
commit 22b9246692
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 36 deletions

View File

@ -68,12 +68,14 @@ export abstract class BrowserContext extends EventEmitter {
readonly _downloads = new Set<Download>(); readonly _downloads = new Set<Download>();
readonly _idToScreencast = new Map<string, Screencast>(); readonly _idToScreencast = new Map<string, Screencast>();
readonly _browser: Browser; readonly _browser: Browser;
readonly _browserContextId: string | undefined;
constructor(browser: Browser, options: types.BrowserContextOptions, isPersistentContext: boolean) { constructor(browser: Browser, options: types.BrowserContextOptions, browserContextId: string | undefined) {
super(); super();
this._browser = browser; this._browser = browser;
this._options = options; this._options = options;
this._isPersistentContext = isPersistentContext; this._browserContextId = browserContextId;
this._isPersistentContext = !browserContextId;
this._closePromise = new Promise(fulfill => this._closePromiseFulfill = fulfill); this._closePromise = new Promise(fulfill => this._closePromiseFulfill = fulfill);
} }

View File

@ -57,7 +57,7 @@ export class CRBrowser extends Browser {
await session.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }); await session.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
return browser; return browser;
} }
browser._defaultContext = new CRBrowserContext(browser, null, options.persistent); browser._defaultContext = new CRBrowserContext(browser, undefined, options.persistent);
const existingTargetAttachPromises: Promise<any>[] = []; const existingTargetAttachPromises: Promise<any>[] = [];
// First page, background pages and their service workers in the persistent context // First page, background pages and their service workers in the persistent context
@ -284,13 +284,11 @@ export class CRBrowserContext extends BrowserContext {
}; };
readonly _browser: CRBrowser; readonly _browser: CRBrowser;
readonly _browserContextId: string | null;
readonly _evaluateOnNewDocumentSources: string[]; readonly _evaluateOnNewDocumentSources: string[];
constructor(browser: CRBrowser, browserContextId: string | null, options: types.BrowserContextOptions) { constructor(browser: CRBrowser, browserContextId: string | undefined, options: types.BrowserContextOptions) {
super(browser, options, !browserContextId); super(browser, options, browserContextId);
this._browser = browser; this._browser = browser;
this._browserContextId = browserContextId;
this._evaluateOnNewDocumentSources = []; this._evaluateOnNewDocumentSources = [];
this._authenticateProxyViaCredentials(); this._authenticateProxyViaCredentials();
} }
@ -301,7 +299,7 @@ export class CRBrowserContext extends BrowserContext {
if (this._browser._options.downloadsPath) { if (this._browser._options.downloadsPath) {
promises.push(this._browser._session.send('Browser.setDownloadBehavior', { promises.push(this._browser._session.send('Browser.setDownloadBehavior', {
behavior: this._options.acceptDownloads ? 'allowAndName' : 'deny', behavior: this._options.acceptDownloads ? 'allowAndName' : 'deny',
browserContextId: this._browserContextId || undefined, browserContextId: this._browserContextId,
downloadPath: this._browser._options.downloadsPath downloadPath: this._browser._options.downloadsPath
})); }));
} }
@ -321,7 +319,7 @@ export class CRBrowserContext extends BrowserContext {
async newPage(): Promise<Page> { async newPage(): Promise<Page> {
assertBrowserContextIsNotOwned(this); assertBrowserContextIsNotOwned(this);
const { targetId } = await this._browser._session.send('Target.createTarget', { url: 'about:blank', browserContextId: this._browserContextId || undefined }); const { targetId } = await this._browser._session.send('Target.createTarget', { url: 'about:blank', browserContextId: this._browserContextId });
const crPage = this._browser._crPages.get(targetId)!; const crPage = this._browser._crPages.get(targetId)!;
const result = await crPage.pageOrError(); const result = await crPage.pageOrError();
if (result instanceof Page) { if (result instanceof Page) {
@ -333,7 +331,7 @@ export class CRBrowserContext extends BrowserContext {
} }
async _doCookies(urls: string[]): Promise<types.NetworkCookie[]> { async _doCookies(urls: string[]): Promise<types.NetworkCookie[]> {
const { cookies } = await this._browser._session.send('Storage.getCookies', { browserContextId: this._browserContextId || undefined }); const { cookies } = await this._browser._session.send('Storage.getCookies', { browserContextId: this._browserContextId });
return network.filterCookies(cookies.map(c => { return network.filterCookies(cookies.map(c => {
const copy: any = { sameSite: 'None', ...c }; const copy: any = { sameSite: 'None', ...c };
delete copy.size; delete copy.size;
@ -344,11 +342,11 @@ export class CRBrowserContext extends BrowserContext {
} }
async addCookies(cookies: types.SetNetworkCookieParam[]) { async addCookies(cookies: types.SetNetworkCookieParam[]) {
await this._browser._session.send('Storage.setCookies', { cookies: network.rewriteCookies(cookies), browserContextId: this._browserContextId || undefined }); await this._browser._session.send('Storage.setCookies', { cookies: network.rewriteCookies(cookies), browserContextId: this._browserContextId });
} }
async clearCookies() { async clearCookies() {
await this._browser._session.send('Storage.clearCookies', { browserContextId: this._browserContextId || undefined }); await this._browser._session.send('Storage.clearCookies', { browserContextId: this._browserContextId });
} }
async _doGrantPermissions(origin: string, permissions: string[]) { async _doGrantPermissions(origin: string, permissions: string[]) {
@ -376,11 +374,11 @@ export class CRBrowserContext extends BrowserContext {
throw new Error('Unknown permission: ' + permission); throw new Error('Unknown permission: ' + permission);
return protocolPermission; return protocolPermission;
}); });
await this._browser._session.send('Browser.grantPermissions', { origin: origin === '*' ? undefined : origin, browserContextId: this._browserContextId || undefined, permissions: filtered }); await this._browser._session.send('Browser.grantPermissions', { origin: origin === '*' ? undefined : origin, browserContextId: this._browserContextId, permissions: filtered });
} }
async _doClearPermissions() { async _doClearPermissions() {
await this._browser._session.send('Browser.resetPermissions', { browserContextId: this._browserContextId || undefined }); await this._browser._session.send('Browser.resetPermissions', { browserContextId: this._browserContextId });
} }
async setGeolocation(geolocation?: types.Geolocation): Promise<void> { async setGeolocation(geolocation?: types.Geolocation): Promise<void> {

View File

@ -42,7 +42,7 @@ export class FFBrowser extends Browser {
browser._initVersion(), browser._initVersion(),
]; ];
if (options.persistent) { if (options.persistent) {
browser._defaultContext = new FFBrowserContext(browser, null, options.persistent); browser._defaultContext = new FFBrowserContext(browser, undefined, options.persistent);
promises.push((browser._defaultContext as FFBrowserContext)._initialize()); promises.push((browser._defaultContext as FFBrowserContext)._initialize());
} }
if (options.proxy) { if (options.proxy) {
@ -165,17 +165,15 @@ export class FFBrowser extends Browser {
export class FFBrowserContext extends BrowserContext { export class FFBrowserContext extends BrowserContext {
readonly _browser: FFBrowser; readonly _browser: FFBrowser;
readonly _browserContextId: string | null;
constructor(browser: FFBrowser, browserContextId: string | null, options: types.BrowserContextOptions) { constructor(browser: FFBrowser, browserContextId: string | undefined, options: types.BrowserContextOptions) {
super(browser, options, !browserContextId); super(browser, options, browserContextId);
this._browser = browser; this._browser = browser;
this._browserContextId = browserContextId;
} }
async _initialize() { async _initialize() {
assert(!this._ffPages().length); assert(!this._ffPages().length);
const browserContextId = this._browserContextId || undefined; const browserContextId = this._browserContextId;
const promises: Promise<any>[] = [ super._initialize() ]; const promises: Promise<any>[] = [ super._initialize() ];
if (this._browser._options.downloadsPath) { if (this._browser._options.downloadsPath) {
promises.push(this._browser._connection.send('Browser.setDownloadOptions', { promises.push(this._browser._connection.send('Browser.setDownloadOptions', {
@ -233,7 +231,7 @@ export class FFBrowserContext extends BrowserContext {
async newPage(): Promise<Page> { async newPage(): Promise<Page> {
assertBrowserContextIsNotOwned(this); assertBrowserContextIsNotOwned(this);
const { targetId } = await this._browser._connection.send('Browser.newPage', { const { targetId } = await this._browser._connection.send('Browser.newPage', {
browserContextId: this._browserContextId || undefined browserContextId: this._browserContextId
}).catch(e => { }).catch(e => {
if (e.message.includes('Failed to override timezone')) if (e.message.includes('Failed to override timezone'))
throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`); throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`);
@ -250,7 +248,7 @@ export class FFBrowserContext extends BrowserContext {
} }
async _doCookies(urls: string[]): Promise<types.NetworkCookie[]> { async _doCookies(urls: string[]): Promise<types.NetworkCookie[]> {
const { cookies } = await this._browser._connection.send('Browser.getCookies', { browserContextId: this._browserContextId || undefined }); const { cookies } = await this._browser._connection.send('Browser.getCookies', { browserContextId: this._browserContextId });
return network.filterCookies(cookies.map(c => { return network.filterCookies(cookies.map(c => {
const copy: any = { ... c }; const copy: any = { ... c };
delete copy.size; delete copy.size;
@ -260,11 +258,11 @@ export class FFBrowserContext extends BrowserContext {
} }
async addCookies(cookies: types.SetNetworkCookieParam[]) { async addCookies(cookies: types.SetNetworkCookieParam[]) {
await this._browser._connection.send('Browser.setCookies', { browserContextId: this._browserContextId || undefined, cookies: network.rewriteCookies(cookies) }); await this._browser._connection.send('Browser.setCookies', { browserContextId: this._browserContextId, cookies: network.rewriteCookies(cookies) });
} }
async clearCookies() { async clearCookies() {
await this._browser._connection.send('Browser.clearCookies', { browserContextId: this._browserContextId || undefined }); await this._browser._connection.send('Browser.clearCookies', { browserContextId: this._browserContextId });
} }
async _doGrantPermissions(origin: string, permissions: string[]) { async _doGrantPermissions(origin: string, permissions: string[]) {
@ -280,17 +278,17 @@ export class FFBrowserContext extends BrowserContext {
throw new Error('Unknown permission: ' + permission); throw new Error('Unknown permission: ' + permission);
return protocolPermission; return protocolPermission;
}); });
await this._browser._connection.send('Browser.grantPermissions', { origin: origin, browserContextId: this._browserContextId || undefined, permissions: filtered}); await this._browser._connection.send('Browser.grantPermissions', { origin: origin, browserContextId: this._browserContextId, permissions: filtered});
} }
async _doClearPermissions() { async _doClearPermissions() {
await this._browser._connection.send('Browser.resetPermissions', { browserContextId: this._browserContextId || undefined }); await this._browser._connection.send('Browser.resetPermissions', { browserContextId: this._browserContextId });
} }
async setGeolocation(geolocation?: types.Geolocation): Promise<void> { async setGeolocation(geolocation?: types.Geolocation): Promise<void> {
verifyGeolocation(geolocation); verifyGeolocation(geolocation);
this._options.geolocation = geolocation; this._options.geolocation = geolocation;
await this._browser._connection.send('Browser.setGeolocationOverride', { browserContextId: this._browserContextId || undefined, geolocation: geolocation || null }); await this._browser._connection.send('Browser.setGeolocationOverride', { browserContextId: this._browserContextId, geolocation: geolocation || null });
} }
async setExtraHTTPHeaders(headers: types.HeadersArray): Promise<void> { async setExtraHTTPHeaders(headers: types.HeadersArray): Promise<void> {
@ -298,34 +296,34 @@ export class FFBrowserContext extends BrowserContext {
let allHeaders = this._options.extraHTTPHeaders; let allHeaders = this._options.extraHTTPHeaders;
if (this._options.locale) if (this._options.locale)
allHeaders = network.mergeHeaders([allHeaders, network.singleHeader('Accept-Language', this._options.locale)]); allHeaders = network.mergeHeaders([allHeaders, network.singleHeader('Accept-Language', this._options.locale)]);
await this._browser._connection.send('Browser.setExtraHTTPHeaders', { browserContextId: this._browserContextId || undefined, headers: allHeaders }); await this._browser._connection.send('Browser.setExtraHTTPHeaders', { browserContextId: this._browserContextId, headers: allHeaders });
} }
async setOffline(offline: boolean): Promise<void> { async setOffline(offline: boolean): Promise<void> {
this._options.offline = offline; this._options.offline = offline;
await this._browser._connection.send('Browser.setOnlineOverride', { browserContextId: this._browserContextId || undefined, override: offline ? 'offline' : 'online' }); await this._browser._connection.send('Browser.setOnlineOverride', { browserContextId: this._browserContextId, override: offline ? 'offline' : 'online' });
} }
async _doSetHTTPCredentials(httpCredentials?: types.Credentials): Promise<void> { async _doSetHTTPCredentials(httpCredentials?: types.Credentials): Promise<void> {
this._options.httpCredentials = httpCredentials; this._options.httpCredentials = httpCredentials;
await this._browser._connection.send('Browser.setHTTPCredentials', { browserContextId: this._browserContextId || undefined, credentials: httpCredentials || null }); await this._browser._connection.send('Browser.setHTTPCredentials', { browserContextId: this._browserContextId, credentials: httpCredentials || null });
} }
async _doAddInitScript(source: string) { async _doAddInitScript(source: string) {
await this._browser._connection.send('Browser.addScriptToEvaluateOnNewDocument', { browserContextId: this._browserContextId || undefined, script: source }); await this._browser._connection.send('Browser.addScriptToEvaluateOnNewDocument', { browserContextId: this._browserContextId, script: source });
} }
async _doExposeBinding(binding: PageBinding) { async _doExposeBinding(binding: PageBinding) {
await this._browser._connection.send('Browser.addBinding', { browserContextId: this._browserContextId || undefined, name: binding.name, script: binding.source }); await this._browser._connection.send('Browser.addBinding', { browserContextId: this._browserContextId, name: binding.name, script: binding.source });
} }
async _doUpdateRequestInterception(): Promise<void> { async _doUpdateRequestInterception(): Promise<void> {
await this._browser._connection.send('Browser.setRequestInterception', { browserContextId: this._browserContextId || undefined, enabled: !!this._requestInterceptor }); await this._browser._connection.send('Browser.setRequestInterception', { browserContextId: this._browserContextId, enabled: !!this._requestInterceptor });
} }
async _enableScreencast(options: types.ContextScreencastOptions): Promise<void> { async _enableScreencast(options: types.ContextScreencastOptions): Promise<void> {
await super._enableScreencast(options); await super._enableScreencast(options);
await this._browser._connection.send('Browser.setScreencastOptions', Object.assign({}, options, { browserContextId: this._browserContextId || undefined})); await this._browser._connection.send('Browser.setScreencastOptions', Object.assign({}, options, { browserContextId: this._browserContextId}));
} }
async _doClose() { async _doClose() {

View File

@ -209,9 +209,8 @@ export class WKBrowserContext extends BrowserContext {
readonly _evaluateOnNewDocumentSources: string[]; readonly _evaluateOnNewDocumentSources: string[];
constructor(browser: WKBrowser, browserContextId: string | undefined, options: types.BrowserContextOptions) { constructor(browser: WKBrowser, browserContextId: string | undefined, options: types.BrowserContextOptions) {
super(browser, options, !browserContextId); super(browser, options, browserContextId);
this._browser = browser; this._browser = browser;
this._browserContextId = browserContextId;
this._evaluateOnNewDocumentSources = []; this._evaluateOnNewDocumentSources = [];
this._authenticateProxyViaHeader(); this._authenticateProxyViaHeader();
} }