|
| 1 | +/** |
| 2 | + * Copyright 2017 Google Inc. All rights reserved. |
| 3 | + * Modifications copyright (c) Microsoft Corporation. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +import { EventEmitter } from 'events'; |
| 19 | +import { Events } from './events'; |
| 20 | +import { Events as CommonEvents } from '../events'; |
| 21 | +import { assert, helper } from '../helper'; |
| 22 | +import { BrowserContext, BrowserContextOptions } from '../browserContext'; |
| 23 | +import { CRConnection, ConnectionEvents, CRSession } from './crConnection'; |
| 24 | +import { Page } from '../page'; |
| 25 | +import { CRTarget } from './crTarget'; |
| 26 | +import { Protocol } from './protocol'; |
| 27 | +import { CRFrameManager } from './crFrameManager'; |
| 28 | +import * as browser from '../browser'; |
| 29 | +import * as network from '../network'; |
| 30 | +import { CRPermissions } from './features/crPermissions'; |
| 31 | +import { CROverrides } from './features/crOverrides'; |
| 32 | +import { Worker } from './features/crWorkers'; |
| 33 | +import { ConnectionTransport } from '../transport'; |
| 34 | +import { readProtocolStream } from './protocolHelper'; |
| 35 | + |
| 36 | +export class CRBrowser extends EventEmitter implements browser.Browser { |
| 37 | + _connection: CRConnection; |
| 38 | + _client: CRSession; |
| 39 | + private _defaultContext: BrowserContext; |
| 40 | + private _contexts = new Map<string, BrowserContext>(); |
| 41 | + _targets = new Map<string, CRTarget>(); |
| 42 | + |
| 43 | + private _tracingRecording = false; |
| 44 | + private _tracingPath = ''; |
| 45 | + private _tracingClient: CRSession | undefined; |
| 46 | + |
| 47 | + static async create( |
| 48 | + transport: ConnectionTransport) { |
| 49 | + const connection = new CRConnection(transport); |
| 50 | + |
| 51 | + const { browserContextIds } = await connection.rootSession.send('Target.getBrowserContexts'); |
| 52 | + const browser = new CRBrowser(connection, browserContextIds); |
| 53 | + await connection.rootSession.send('Target.setDiscoverTargets', { discover: true }); |
| 54 | + await browser.waitForTarget(t => t.type() === 'page'); |
| 55 | + return browser; |
| 56 | + } |
| 57 | + |
| 58 | + constructor(connection: CRConnection, contextIds: string[]) { |
| 59 | + super(); |
| 60 | + this._connection = connection; |
| 61 | + this._client = connection.rootSession; |
| 62 | + |
| 63 | + this._defaultContext = this._createBrowserContext(null, {}); |
| 64 | + for (const contextId of contextIds) |
| 65 | + this._contexts.set(contextId, this._createBrowserContext(contextId, {})); |
| 66 | + |
| 67 | + this._connection.on(ConnectionEvents.Disconnected, () => this.emit(CommonEvents.Browser.Disconnected)); |
| 68 | + this._client.on('Target.targetCreated', this._targetCreated.bind(this)); |
| 69 | + this._client.on('Target.targetDestroyed', this._targetDestroyed.bind(this)); |
| 70 | + this._client.on('Target.targetInfoChanged', this._targetInfoChanged.bind(this)); |
| 71 | + } |
| 72 | + |
| 73 | + _createBrowserContext(contextId: string | null, options: BrowserContextOptions): BrowserContext { |
| 74 | + let overrides: CROverrides | null = null; |
| 75 | + const context = new BrowserContext({ |
| 76 | + pages: async (): Promise<Page[]> => { |
| 77 | + const targets = this._allTargets().filter(target => target.browserContext() === context && target.type() === 'page'); |
| 78 | + const pages = await Promise.all(targets.map(target => target.page())); |
| 79 | + return pages.filter(page => !!page); |
| 80 | + }, |
| 81 | + |
| 82 | + newPage: async (): Promise<Page> => { |
| 83 | + const { targetId } = await this._client.send('Target.createTarget', { url: 'about:blank', browserContextId: contextId || undefined }); |
| 84 | + const target = this._targets.get(targetId); |
| 85 | + assert(await target._initializedPromise, 'Failed to create target for page'); |
| 86 | + const page = await target.page(); |
| 87 | + const session = (page._delegate as CRFrameManager)._client; |
| 88 | + const promises: Promise<any>[] = [ overrides._applyOverrides(page) ]; |
| 89 | + if (options.bypassCSP) |
| 90 | + promises.push(session.send('Page.setBypassCSP', { enabled: true })); |
| 91 | + if (options.ignoreHTTPSErrors) |
| 92 | + promises.push(session.send('Security.setIgnoreCertificateErrors', { ignore: true })); |
| 93 | + if (options.viewport) |
| 94 | + promises.push(page._delegate.setViewport(options.viewport)); |
| 95 | + if (options.javaScriptEnabled === false) |
| 96 | + promises.push(session.send('Emulation.setScriptExecutionDisabled', { value: true })); |
| 97 | + if (options.userAgent) |
| 98 | + (page._delegate as CRFrameManager)._networkManager.setUserAgent(options.userAgent); |
| 99 | + if (options.mediaType || options.colorScheme) { |
| 100 | + const features = options.colorScheme ? [{ name: 'prefers-color-scheme', value: options.colorScheme }] : []; |
| 101 | + promises.push(session.send('Emulation.setEmulatedMedia', { media: options.mediaType || '', features })); |
| 102 | + } |
| 103 | + if (options.timezoneId) |
| 104 | + promises.push(emulateTimezone(session, options.timezoneId)); |
| 105 | + await Promise.all(promises); |
| 106 | + return page; |
| 107 | + }, |
| 108 | + |
| 109 | + close: async (): Promise<void> => { |
| 110 | + assert(contextId, 'Non-incognito profiles cannot be closed!'); |
| 111 | + await this._client.send('Target.disposeBrowserContext', {browserContextId: contextId || undefined}); |
| 112 | + this._contexts.delete(contextId); |
| 113 | + }, |
| 114 | + |
| 115 | + cookies: async (): Promise<network.NetworkCookie[]> => { |
| 116 | + const { cookies } = await this._client.send('Storage.getCookies', { browserContextId: contextId || undefined }); |
| 117 | + return cookies.map(c => { |
| 118 | + const copy: any = { sameSite: 'None', ...c }; |
| 119 | + delete copy.size; |
| 120 | + delete copy.priority; |
| 121 | + return copy as network.NetworkCookie; |
| 122 | + }); |
| 123 | + }, |
| 124 | + |
| 125 | + clearCookies: async (): Promise<void> => { |
| 126 | + await this._client.send('Storage.clearCookies', { browserContextId: contextId || undefined }); |
| 127 | + }, |
| 128 | + |
| 129 | + setCookies: async (cookies: network.SetNetworkCookieParam[]): Promise<void> => { |
| 130 | + await this._client.send('Storage.setCookies', { cookies, browserContextId: contextId || undefined }); |
| 131 | + }, |
| 132 | + }, options); |
| 133 | + overrides = new CROverrides(context); |
| 134 | + (context as any).permissions = new CRPermissions(this._client, contextId); |
| 135 | + (context as any).overrides = overrides; |
| 136 | + return context; |
| 137 | + } |
| 138 | + |
| 139 | + async newContext(options: BrowserContextOptions = {}): Promise<BrowserContext> { |
| 140 | + const { browserContextId } = await this._client.send('Target.createBrowserContext'); |
| 141 | + const context = this._createBrowserContext(browserContextId, options); |
| 142 | + this._contexts.set(browserContextId, context); |
| 143 | + return context; |
| 144 | + } |
| 145 | + |
| 146 | + browserContexts(): BrowserContext[] { |
| 147 | + return [this._defaultContext, ...Array.from(this._contexts.values())]; |
| 148 | + } |
| 149 | + |
| 150 | + defaultContext(): BrowserContext { |
| 151 | + return this._defaultContext; |
| 152 | + } |
| 153 | + |
| 154 | + async _targetCreated(event: Protocol.Target.targetCreatedPayload) { |
| 155 | + const targetInfo = event.targetInfo; |
| 156 | + const {browserContextId} = targetInfo; |
| 157 | + const context = (browserContextId && this._contexts.has(browserContextId)) ? this._contexts.get(browserContextId) : this._defaultContext; |
| 158 | + |
| 159 | + const target = new CRTarget(this, targetInfo, context, () => this._connection.createSession(targetInfo)); |
| 160 | + assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated'); |
| 161 | + this._targets.set(event.targetInfo.targetId, target); |
| 162 | + |
| 163 | + if (target._isInitialized || await target._initializedPromise) |
| 164 | + this.emit(Events.Browser.TargetCreated, target); |
| 165 | + } |
| 166 | + |
| 167 | + async _targetDestroyed(event: { targetId: string; }) { |
| 168 | + const target = this._targets.get(event.targetId); |
| 169 | + target._initializedCallback(false); |
| 170 | + this._targets.delete(event.targetId); |
| 171 | + target._didClose(); |
| 172 | + if (await target._initializedPromise) |
| 173 | + this.emit(Events.Browser.TargetDestroyed, target); |
| 174 | + } |
| 175 | + |
| 176 | + _targetInfoChanged(event: Protocol.Target.targetInfoChangedPayload) { |
| 177 | + const target = this._targets.get(event.targetInfo.targetId); |
| 178 | + assert(target, 'target should exist before targetInfoChanged'); |
| 179 | + const previousURL = target.url(); |
| 180 | + const wasInitialized = target._isInitialized; |
| 181 | + target._targetInfoChanged(event.targetInfo); |
| 182 | + if (wasInitialized && previousURL !== target.url()) |
| 183 | + this.emit(Events.Browser.TargetChanged, target); |
| 184 | + } |
| 185 | + |
| 186 | + async _closePage(page: Page) { |
| 187 | + await this._client.send('Target.closeTarget', { targetId: CRTarget.fromPage(page)._targetId }); |
| 188 | + } |
| 189 | + |
| 190 | + _allTargets(): CRTarget[] { |
| 191 | + return Array.from(this._targets.values()).filter(target => target._isInitialized); |
| 192 | + } |
| 193 | + |
| 194 | + async _activatePage(page: Page) { |
| 195 | + await (page._delegate as CRFrameManager)._client.send('Target.activateTarget', {targetId: CRTarget.fromPage(page)._targetId}); |
| 196 | + } |
| 197 | + |
| 198 | + async waitForTarget(predicate: (arg0: CRTarget) => boolean, options: { timeout?: number; } | undefined = {}): Promise<CRTarget> { |
| 199 | + const { |
| 200 | + timeout = 30000 |
| 201 | + } = options; |
| 202 | + const existingTarget = this._allTargets().find(predicate); |
| 203 | + if (existingTarget) |
| 204 | + return existingTarget; |
| 205 | + let resolve: (target: CRTarget) => void; |
| 206 | + const targetPromise = new Promise<CRTarget>(x => resolve = x); |
| 207 | + this.on(Events.Browser.TargetCreated, check); |
| 208 | + this.on(Events.Browser.TargetChanged, check); |
| 209 | + try { |
| 210 | + if (!timeout) |
| 211 | + return await targetPromise; |
| 212 | + return await helper.waitWithTimeout(targetPromise, 'target', timeout); |
| 213 | + } finally { |
| 214 | + this.removeListener(Events.Browser.TargetCreated, check); |
| 215 | + this.removeListener(Events.Browser.TargetChanged, check); |
| 216 | + } |
| 217 | + |
| 218 | + function check(target: CRTarget) { |
| 219 | + if (predicate(target)) |
| 220 | + resolve(target); |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + async close() { |
| 225 | + await this._connection.rootSession.send('Browser.close'); |
| 226 | + this.disconnect(); |
| 227 | + } |
| 228 | + |
| 229 | + browserTarget(): CRTarget { |
| 230 | + return [...this._targets.values()].find(t => t.type() === 'browser'); |
| 231 | + } |
| 232 | + |
| 233 | + serviceWorker(target: CRTarget): Promise<Worker | null> { |
| 234 | + return target._worker(); |
| 235 | + } |
| 236 | + |
| 237 | + async startTracing(page: Page | undefined, options: { path?: string; screenshots?: boolean; categories?: string[]; } = {}) { |
| 238 | + assert(!this._tracingRecording, 'Cannot start recording trace while already recording trace.'); |
| 239 | + this._tracingClient = page ? (page._delegate as CRFrameManager)._client : this._client; |
| 240 | + |
| 241 | + const defaultCategories = [ |
| 242 | + '-*', 'devtools.timeline', 'v8.execute', 'disabled-by-default-devtools.timeline', |
| 243 | + 'disabled-by-default-devtools.timeline.frame', 'toplevel', |
| 244 | + 'blink.console', 'blink.user_timing', 'latencyInfo', 'disabled-by-default-devtools.timeline.stack', |
| 245 | + 'disabled-by-default-v8.cpu_profiler', 'disabled-by-default-v8.cpu_profiler.hires' |
| 246 | + ]; |
| 247 | + const { |
| 248 | + path = null, |
| 249 | + screenshots = false, |
| 250 | + categories = defaultCategories, |
| 251 | + } = options; |
| 252 | + |
| 253 | + if (screenshots) |
| 254 | + categories.push('disabled-by-default-devtools.screenshot'); |
| 255 | + |
| 256 | + this._tracingPath = path; |
| 257 | + this._tracingRecording = true; |
| 258 | + await this._tracingClient.send('Tracing.start', { |
| 259 | + transferMode: 'ReturnAsStream', |
| 260 | + categories: categories.join(',') |
| 261 | + }); |
| 262 | + } |
| 263 | + |
| 264 | + async stopTracing(): Promise<Buffer> { |
| 265 | + assert(this._tracingClient, 'Tracing was not started.'); |
| 266 | + let fulfill: (buffer: Buffer) => void; |
| 267 | + const contentPromise = new Promise<Buffer>(x => fulfill = x); |
| 268 | + this._tracingClient.once('Tracing.tracingComplete', event => { |
| 269 | + readProtocolStream(this._tracingClient, event.stream, this._tracingPath).then(fulfill); |
| 270 | + }); |
| 271 | + await this._tracingClient.send('Tracing.end'); |
| 272 | + this._tracingRecording = false; |
| 273 | + return contentPromise; |
| 274 | + } |
| 275 | + |
| 276 | + targets(context?: BrowserContext): CRTarget[] { |
| 277 | + const targets = this._allTargets(); |
| 278 | + return context ? targets.filter(t => t.browserContext() === context) : targets; |
| 279 | + } |
| 280 | + |
| 281 | + pageTarget(page: Page): CRTarget { |
| 282 | + return CRTarget.fromPage(page); |
| 283 | + } |
| 284 | + |
| 285 | + disconnect() { |
| 286 | + this._connection.dispose(); |
| 287 | + } |
| 288 | + |
| 289 | + isConnected(): boolean { |
| 290 | + return !this._connection._closed; |
| 291 | + } |
| 292 | +} |
| 293 | + |
| 294 | +async function emulateTimezone(session: CRSession, timezoneId: string) { |
| 295 | + try { |
| 296 | + await session.send('Emulation.setTimezoneOverride', { timezoneId: timezoneId }); |
| 297 | + } catch (exception) { |
| 298 | + if (exception.message.includes('Invalid timezone')) |
| 299 | + throw new Error(`Invalid timezone ID: ${timezoneId}`); |
| 300 | + throw exception; |
| 301 | + } |
| 302 | +} |
0 commit comments