1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465/**
* Copyright 2018 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.
*/
import { assert } from '../../utils';
import { Browser } from '../browser';
import { BrowserContext, verifyGeolocation } from '../browserContext';
import { TargetClosedError } from '../errors';
import * as network from '../network';
import { ConnectionEvents, FFConnection } from './ffConnection';
import { FFPage } from './ffPage';
import { PageBinding } from '../page';
import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { InitScript, Page } from '../page';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';
import type { FFSession } from './ffConnection';
import type { Protocol } from './protocol';
import type * as channels from '@protocol/channels';
export class FFBrowser extends Browser {
private _connection: FFConnection;
readonly session: FFSession;
readonly _ffPages: Map<string, FFPage>;
readonly _contexts: Map<string, FFBrowserContext>;
private _version = '';
private _userAgent: string = '';
static async connect(parent: SdkObject, transport: ConnectionTransport, options: BrowserOptions): Promise<FFBrowser> {
const connection = new FFConnection(transport, options.protocolLogger, options.browserLogsCollector);
const browser = new FFBrowser(parent, connection, options);
if ((options as any).__testHookOnConnectToBrowser)
await (options as any).__testHookOnConnectToBrowser();
let firefoxUserPrefs = options.originalLaunchOptions.firefoxUserPrefs ?? {};
if (Object.keys(kBandaidFirefoxUserPrefs).length)
firefoxUserPrefs = { ...kBandaidFirefoxUserPrefs, ...firefoxUserPrefs };
const promises: Promise<any>[] = [
browser.session.send('Browser.enable', {
attachToDefaultContext: !!options.persistent,
userPrefs: Object.entries(firefoxUserPrefs).map(([name, value]) => ({ name, value })),
}),
browser._initVersion(),
];
if (options.persistent) {
browser._defaultContext = new FFBrowserContext(browser, undefined, options.persistent);
promises.push((browser._defaultContext as FFBrowserContext)._initialize());
}
const proxy = options.originalLaunchOptions.proxyOverride || options.proxy;
if (proxy)
promises.push(browser.session.send('Browser.setBrowserProxy', toJugglerProxyOptions(proxy)));
await Promise.all(promises);
return browser;
}
constructor(parent: SdkObject, connection: FFConnection, options: BrowserOptions) {
super(parent, options);
this._connection = connection;
this.session = connection.rootSession;
this._ffPages = new Map();
this._contexts = new Map();
this._connection.on(ConnectionEvents.Disconnected, () => this._onDisconnect());
this.session.on('Browser.attachedToTarget', this._onAttachedToTarget.bind(this));
this.session.on('Browser.detachedFromTarget', this._onDetachedFromTarget.bind(this));
this.session.on('Browser.downloadCreated', this._onDownloadCreated.bind(this));
this.session.on('Browser.downloadFinished', this._onDownloadFinished.bind(this));
}
async _initVersion() {
const result = await this.session.send('Browser.getInfo');
this._version = result.version.substring(result.version.indexOf('/') + 1);
this._userAgent = result.userAgent;
}
isConnected(): boolean {
return !this._connection._closed;
}
async doCreateNewContext(options: types.BrowserContextOptions): Promise<BrowserContext> {
if (options.isMobile)
throw new Error('options.isMobile is not supported in Firefox');
const { browserContextId } = await this.session.send('Browser.createBrowserContext', { removeOnDetach: true });
const context = new FFBrowserContext(this, browserContextId, options);
await context._initialize();
this._contexts.set(browserContextId, context);
return context;
}
contexts(): BrowserContext[] {
return Array.from(this._contexts.values());
}
version(): string {
return this._version;
}
userAgent(): string {
return this._userAgent;
}
_onDetachedFromTarget(payload: Protocol.Browser.detachedFromTargetPayload) {
const ffPage = this._ffPages.get(payload.targetId)!;
this._ffPages.delete(payload.targetId);
ffPage.didClose();
}
_onAttachedToTarget(payload: Protocol.Browser.attachedToTargetPayload) {
const { targetId, browserContextId, openerId, type } = payload.targetInfo;
assert(type === 'page');
const context = browserContextId ? this._contexts.get(browserContextId)! : this._defaultContext as FFBrowserContext;
assert(context, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`);
const session = this._connection.createSession(payload.sessionId);
const opener = openerId ? this._ffPages.get(openerId)! : null;
const ffPage = new FFPage(session, context, opener);
this._ffPages.set(targetId, ffPage);
}
_onDownloadCreated(payload: Protocol.Browser.downloadCreatedPayload) {
const ffPage = this._ffPages.get(payload.pageTargetId);
if (!ffPage)
return;
// Abort the navigation that turned into download.
ffPage._page.frameManager.frameAbortedNavigation(payload.frameId, 'Download is starting');
let originPage = ffPage._page.initializedOrUndefined();
// If it's a new window download, report it on the opener page.
if (!originPage) {
// Resume the page creation with an error. The page will automatically close right
// after the download begins.
ffPage._markAsError(new Error('Starting new page download'));
if (ffPage._opener)
originPage = ffPage._opener._page.initializedOrUndefined();
}
if (!originPage)
return;
this._downloadCreated(originPage, payload.uuid, payload.url, payload.suggestedFileName);
}
_onDownloadFinished(payload: Protocol.Browser.downloadFinishedPayload) {
const error = payload.canceled ? 'canceled' : payload.error;
this._downloadFinished(payload.uuid, error);
}
_onDisconnect() {
for (const video of this._idToVideo.values())
video.artifact.reportFinished(new TargetClosedError(this.closeReason()));
this._idToVideo.clear();
for (const ffPage of this._ffPages.values())
ffPage.didClose();
this._ffPages.clear();
this._didClose();
}
}
export class FFBrowserContext extends BrowserContext {
declare readonly _browser: FFBrowser;
constructor(browser: FFBrowser, browserContextId: string | undefined, options: types.BrowserContextOptions) {
super(browser, options, browserContextId);
}
override async _initialize() {
assert(!this._ffPages().length);
const browserContextId = this._browserContextId;
const promises: Promise<any>[] = [
super._initialize(),
this._updateInitScripts(),
];
if (this._options.acceptDownloads !== 'internal-browser-default') {
promises.push(this._browser.session.send('Browser.setDownloadOptions', {
browserContextId,
downloadOptions: {
behavior: this._options.acceptDownloads === 'accept' ? 'saveToDisk' : 'cancel',
downloadsDir: this._browser.options.downloadsPath,
},
}));
}
promises.push(this.doUpdateDefaultViewport());
if (this._options.hasTouch)
promises.push(this._browser.session.send('Browser.setTouchOverride', { browserContextId, hasTouch: true }));
if (this._options.userAgent)
promises.push(this._browser.session.send('Browser.setUserAgentOverride', { browserContextId, userAgent: this._options.userAgent }));
if (this._options.bypassCSP)
promises.push(this._browser.session.send('Browser.setBypassCSP', { browserContextId, bypassCSP: true }));
if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors)
promises.push(this._browser.session.send('Browser.setIgnoreHTTPSErrors', { browserContextId, ignoreHTTPSErrors: true }));
if (this._options.javaScriptEnabled === false)
promises.push(this._browser.session.send('Browser.setJavaScriptDisabled', { browserContextId, javaScriptDisabled: true }));
if (this._options.locale)
promises.push(this._browser.session.send('Browser.setLocaleOverride', { browserContextId, locale: this._options.locale }));
if (this._options.timezoneId)
promises.push(this._browser.session.send('Browser.setTimezoneOverride', { browserContextId, timezoneId: this._options.timezoneId }));
if (this._options.extraHTTPHeaders || this._options.locale)
promises.push(this.doUpdateExtraHTTPHeaders());
if (this._options.httpCredentials)
promises.push(this.setHTTPCredentials(this._options.httpCredentials));
if (this._options.geolocation)
promises.push(this.setGeolocation(this._options.geolocation));
if (this._options.offline)
promises.push(this.doUpdateOffline());
promises.push(this.doUpdateDefaultEmulatedMedia());
if (this._options.recordVideo) {
promises.push(this._browser.session.send('Browser.setScreencastOptions', {
// validateBrowserContextOptions ensures correct video size.
options: {
...this._options.recordVideo!.size!,
quality: 90,
},
browserContextId: this._browserContextId
}));
}
const proxy = this._options.proxyOverride || this._options.proxy;
if (proxy) {
promises.push(this._browser.session.send('Browser.setContextProxy', {
browserContextId: this._browserContextId,
...toJugglerProxyOptions(proxy)
}));
}
await Promise.all(promises);
}
_ffPages(): FFPage[] {
return Array.from(this._browser._ffPages.values()).filter(ffPage => ffPage._browserContext === this);
}
override possiblyUninitializedPages(): Page[] {
return this._ffPages().map(ffPage => ffPage._page);
}
override async doCreateNewPage(): Promise<Page> {
const { targetId } = await this._browser.session.send('Browser.newPage', {
browserContextId: this._browserContextId
}).catch(e => {
if (e.message.includes('Failed to override timezone'))
throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`);
throw e;
});
return this._browser._ffPages.get(targetId)!._page;
}
async doGetCookies(urls: string[]): Promise<channels.NetworkCookie[]> {
const { cookies } = await this._browser.session.send('Browser.getCookies', { browserContextId: this._browserContextId });
return network.filterCookies(cookies.map(c => {
const { name, value, domain, path, expires, httpOnly, secure, sameSite } = c;
return {
name,
value,
domain,
path,
expires,
httpOnly,
secure,
sameSite,
};
}), urls);
}
async addCookies(cookies: channels.SetNetworkCookie[]) {
const cc = network.rewriteCookies(cookies).map(c => {
const { name, value, url, domain, path, expires, httpOnly, secure, sameSite } = c;
return {
name,
value,
url,
domain,
path,
expires: expires === -1 ? undefined : expires,
httpOnly,
secure,
sameSite
};
});
await this._browser.session.send('Browser.setCookies', { browserContextId: this._browserContextId, cookies: cc });
}
async doClearCookies() {
await this._browser.session.send('Browser.clearCookies', { browserContextId: this._browserContextId });
}
async doGrantPermissions(origin: string, permissions: string[]) {
const webPermissionToProtocol = new Map<string, 'geo' | 'desktop-notification' | 'persistent-storage' | 'push'>([
['geolocation', 'geo'],
['persistent-storage', 'persistent-storage'],
['push', 'push'],
['notifications', 'desktop-notification'],
]);
const filtered = permissions.map(permission => {
const protocolPermission = webPermissionToProtocol.get(permission);
if (!protocolPermission)
throw new Error('Unknown permission: ' + permission);
return protocolPermission;
});
await this._browser.session.send('Browser.grantPermissions', { origin: origin, browserContextId: this._browserContextId, permissions: filtered });
}
async doClearPermissions() {
await this._browser.session.send('Browser.resetPermissions', { browserContextId: this._browserContextId });
}
async setGeolocation(geolocation?: types.Geolocation): Promise<void> {
verifyGeolocation(geolocation);
this._options.geolocation = geolocation;
await this._browser.session.send('Browser.setGeolocationOverride', { browserContextId: this._browserContextId, geolocation: geolocation || null });
}
async doUpdateExtraHTTPHeaders(): Promise<void> {
let allHeaders = this._options.extraHTTPHeaders || [];
if (this._options.locale)
allHeaders = network.mergeHeaders([allHeaders, network.singleHeader('Accept-Language', this._options.locale)]);
await this._browser.session.send('Browser.setExtraHTTPHeaders', { browserContextId: this._browserContextId, headers: allHeaders });
}
async setUserAgent(userAgent: string | undefined): Promise<void> {
await this._browser.session.send('Browser.setUserAgentOverride', { browserContextId: this._browserContextId, userAgent: userAgent || null });
}
async doUpdateOffline(): Promise<void> {
await this._browser.session.send('Browser.setOnlineOverride', { browserContextId: this._browserContextId, override: this._options.offline ? 'offline' : 'online' });
}
async doSetHTTPCredentials(httpCredentials?: types.Credentials): Promise<void> {
this._options.httpCredentials = httpCredentials;
let credentials = null;
if (httpCredentials) {
const { username, password, origin } = httpCredentials;
credentials = { username, password, origin };
}
await this._browser.session.send('Browser.setHTTPCredentials', { browserContextId: this._browserContextId, credentials });
}
async doAddInitScript(initScript: InitScript) {
await this._updateInitScripts();
}
async doRemoveInitScripts(initScripts: InitScript[]) {
await this._updateInitScripts();
}
private async _updateInitScripts() {
const bindingScripts = [...this._pageBindings.values()].map(binding => binding.initScript.source);
if (this.bindingsInitScript)
bindingScripts.unshift(this.bindingsInitScript.source);
const initScripts = this.initScripts.map(script => script.source);
await this._browser.session.send('Browser.setInitScripts', { browserContextId: this._browserContextId, scripts: [...bindingScripts, ...initScripts].map(script => ({ script })) });
}
async doUpdateRequestInterception(): Promise<void> {
await Promise.all([
this._browser.session.send('Browser.setRequestInterception', { browserContextId: this._browserContextId, enabled: this.requestInterceptors.length > 0 }),
this._browser.session.send('Browser.setCacheDisabled', { browserContextId: this._browserContextId, cacheDisabled: this.requestInterceptors.length > 0 }),
]);
}
override async doUpdateDefaultViewport() {
if (!this._options.viewport)
return;
const viewport = {
viewportSize: { width: this._options.viewport.width, height: this._options.viewport.height },
deviceScaleFactor: this._options.deviceScaleFactor || 1,
};
await this._browser.session.send('Browser.setDefaultViewport', { browserContextId: this._browserContextId, viewport });
}
override async doUpdateDefaultEmulatedMedia() {
if (this._options.colorScheme !== 'no-override') {
await this._browser.session.send('Browser.setColorScheme', {
browserContextId: this._browserContextId,
colorScheme: this._options.colorScheme !== undefined ? this._options.colorScheme : 'light',
});
}
if (this._options.reducedMotion !== 'no-override') {
await this._browser.session.send('Browser.setReducedMotion', {
browserContextId: this._browserContextId,
reducedMotion: this._options.reducedMotion !== undefined ? this._options.reducedMotion : 'no-preference',
});
}
if (this._options.forcedColors !== 'no-override') {
await this._browser.session.send('Browser.setForcedColors', {
browserContextId: this._browserContextId,
forcedColors: this._options.forcedColors !== undefined ? this._options.forcedColors : 'none',
});
}
if (this._options.contrast !== 'no-override') {
await this._browser.session.send('Browser.setContrast', {
browserContextId: this._browserContextId,
contrast: this._options.contrast !== undefined ? this._options.contrast : 'no-preference',
});
}
}
override async doExposePlaywrightBinding() {
this._browser.session.send('Browser.addBinding', { browserContextId: this._browserContextId, name: PageBinding.kBindingName, script: '' });
}
onClosePersistent() {}
override async clearCache(): Promise<void> {
// Clearing only the context cache does not work: https://bugzilla.mozilla.org/show_bug.cgi?id=1819147
await this._browser.session.send('Browser.clearCache');
}
async doClose(reason: string | undefined) {
if (!this._browserContextId) {
if (this._options.recordVideo)
await Promise.all(this._ffPages().map(ffPage => ffPage._page.screencast.stopVideoRecording()));
// Closing persistent context should close the browser.
await this._browser.close({ reason });
} else {
await this._browser.session.send('Browser.removeBrowserContext', { browserContextId: this._browserContextId });
this._browser._contexts.delete(this._browserContextId);
}
}
async cancelDownload(uuid: string) {
await this._browser.session.send('Browser.cancelDownload', { uuid });
}
}
function toJugglerProxyOptions(proxy: types.ProxySettings) {
const proxyServer = new URL(proxy.server);
let port = parseInt(proxyServer.port, 10);
let type: 'http' | 'https' | 'socks' | 'socks4' = 'http';
if (proxyServer.protocol === 'socks5:')
type = 'socks';
else if (proxyServer.protocol === 'socks4:')
type = 'socks4';
else if (proxyServer.protocol === 'https:')
type = 'https';
if (proxyServer.port === '') {
if (proxyServer.protocol === 'http:')
port = 80;
else if (proxyServer.protocol === 'https:')
port = 443;
}
return {
type,
bypass: proxy.bypass ? proxy.bypass.split(',').map(domain => domain.trim()) : [],
host: proxyServer.hostname,
port,
username: proxy.username,
password: proxy.password
};
}
// Prefs for quick fixes that didn't make it to the build.
// Should all be moved to `playwright.cfg`.
const kBandaidFirefoxUserPrefs = {
};