UNPKG

7.3 kBJavaScriptView Raw
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const {helper} = require('./helper');
18const Page = require('./Page');
19const EventEmitter = require('events');
20
21class Browser extends EventEmitter {
22 /**
23 * @param {!Puppeteer.Connection} connection
24 * @param {!Object=} options
25 * @param {?Puppeteer.ChildProcess} process
26 * @param {(function():Promise)=} closeCallback
27 */
28 constructor(connection, options = {}, process, closeCallback) {
29 super();
30 this._ignoreHTTPSErrors = !!options.ignoreHTTPSErrors;
31 this._appMode = !!options.appMode;
32 this._process = process;
33 this._screenshotTaskQueue = new TaskQueue();
34 this._connection = connection;
35 this._closeCallback = closeCallback || new Function();
36 /** @type {Map<string, Target>} */
37 this._targets = new Map();
38 this._connection.setClosedCallback(() => {
39 this.emit(Browser.Events.Disconnected);
40 });
41 this._connection.on('Target.targetCreated', this._targetCreated.bind(this));
42 this._connection.on('Target.targetDestroyed', this._targetDestroyed.bind(this));
43 this._connection.on('Target.targetInfoChanged', this._targetInfoChanged.bind(this));
44 }
45
46 /**
47 * @return {?Puppeteer.ChildProcess}
48 */
49 process() {
50 return this._process;
51 }
52
53 /**
54 * @param {!Puppeteer.Connection} connection
55 * @param {!Object=} options
56 * @param {?Puppeteer.ChildProcess} process
57 * @param {function()=} closeCallback
58 */
59 static async create(connection, options, process, closeCallback) {
60 const browser = new Browser(connection, options, process, closeCallback);
61 await connection.send('Target.setDiscoverTargets', {discover: true});
62 return browser;
63 }
64
65 /**
66 * @param {{targetInfo: !Target.TargetInfo}} event
67 */
68 async _targetCreated(event) {
69 const target = new Target(this, event.targetInfo);
70 console.assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated');
71 this._targets.set(event.targetInfo.targetId, target);
72
73 if (await target._initializedPromise)
74 this.emit(Browser.Events.TargetCreated, target);
75 }
76
77 /**
78 * @param {{targetId: string}} event
79 */
80 async _targetDestroyed(event) {
81 const target = this._targets.get(event.targetId);
82 target._initializedCallback(false);
83 this._targets.delete(event.targetId);
84 if (await target._initializedPromise)
85 this.emit(Browser.Events.TargetDestroyed, target);
86 }
87
88 /**
89 * @param {{targetInfo: !Target.TargetInfo}} event
90 */
91 _targetInfoChanged(event) {
92 const target = this._targets.get(event.targetInfo.targetId);
93 console.assert(target, 'target should exist before targetInfoChanged');
94 target._targetInfoChanged(event.targetInfo);
95 }
96
97 /**
98 * @return {string}
99 */
100 wsEndpoint() {
101 return this._connection.url();
102 }
103
104 /**
105 * @return {!Promise<!Page>}
106 */
107 async newPage() {
108 const {targetId} = await this._connection.send('Target.createTarget', {url: 'about:blank'});
109 const target = await this._targets.get(targetId);
110 console.assert(await target._initializedPromise, 'Failed to create target for page');
111 const page = await target.page();
112 return page;
113 }
114
115 /**
116 * @return {!Array<!Target>}
117 */
118 targets() {
119 return Array.from(this._targets.values()).filter(target => target._isInitialized);
120 }
121
122 /**
123 * @return {!Promise<!Array<!Page>>}
124 */
125 async pages() {
126 const pages = await Promise.all(this.targets().map(target => target.page()));
127 return pages.filter(page => !!page);
128 }
129
130 /**
131 * @return {!Promise<string>}
132 */
133 async version() {
134 const version = await this._getVersion();
135 return version.product;
136 }
137
138 /**
139 * @return {!Promise<string>}
140 */
141 async userAgent() {
142 const version = await this._getVersion();
143 return version.userAgent;
144 }
145
146 async close() {
147 await this._closeCallback.call(null);
148 this.disconnect();
149 }
150
151 disconnect() {
152 this._connection.dispose();
153 }
154
155 /**
156 * @return {!Promise<!Object>}
157 */
158 _getVersion() {
159 return this._connection.send('Browser.getVersion');
160 }
161}
162
163/** @enum {string} */
164Browser.Events = {
165 TargetCreated: 'targetcreated',
166 TargetDestroyed: 'targetdestroyed',
167 TargetChanged: 'targetchanged',
168 Disconnected: 'disconnected'
169};
170
171helper.tracePublicAPI(Browser);
172
173class TaskQueue {
174 constructor() {
175 this._chain = Promise.resolve();
176 }
177
178 /**
179 * @param {function()} task
180 * @return {!Promise}
181 */
182 postTask(task) {
183 const result = this._chain.then(task);
184 this._chain = result.catch(() => {});
185 return result;
186 }
187}
188
189class Target {
190 /**
191 * @param {!Browser} browser
192 * @param {!Target.TargetInfo} targetInfo
193 */
194 constructor(browser, targetInfo) {
195 this._browser = browser;
196 this._targetId = targetInfo.targetId;
197 this._targetInfo = targetInfo;
198 /** @type {?Promise<!Page>} */
199 this._pagePromise = null;
200 this._initializedPromise = new Promise(fulfill => this._initializedCallback = fulfill);
201 this._isInitialized = this._targetInfo.type !== 'page' || this._targetInfo.url !== '';
202 if (this._isInitialized)
203 this._initializedCallback(true);
204 }
205
206 /**
207 * @return {!Promise<!Puppeteer.CDPSession>}
208 */
209 createCDPSession() {
210 return this._browser._connection.createSession(this._targetId);
211 }
212
213 /**
214 * @return {!Promise<?Page>}
215 */
216 async page() {
217 if (this._targetInfo.type === 'page' && !this._pagePromise) {
218 this._pagePromise = this._browser._connection.createSession(this._targetId)
219 .then(client => Page.create(client, this, this._browser._ignoreHTTPSErrors, this._browser._appMode, this._browser._screenshotTaskQueue));
220 }
221 return this._pagePromise;
222 }
223
224 /**
225 * @return {string}
226 */
227 url() {
228 return this._targetInfo.url;
229 }
230
231 /**
232 * @return {"page"|"service_worker"|"other"}
233 */
234 type() {
235 const type = this._targetInfo.type;
236 if (type === 'page' || type === 'service_worker')
237 return type;
238 return 'other';
239 }
240
241 /**
242 * @param {!Target.TargetInfo} targetInfo
243 */
244 _targetInfoChanged(targetInfo) {
245 const previousURL = this._targetInfo.url;
246 this._targetInfo = targetInfo;
247
248 if (!this._isInitialized && (this._targetInfo.type !== 'page' || this._targetInfo.url !== '')) {
249 this._isInitialized = true;
250 this._initializedCallback(true);
251 return;
252 }
253
254 if (previousURL !== targetInfo.url)
255 this._browser.emit(Browser.Events.TargetChanged, this);
256 }
257}
258helper.tracePublicAPI(Target);
259
260/**
261 * @typedef {Object} Target.TargetInfo
262 * @property {string} type
263 * @property {string} targetId
264 * @property {string} title
265 * @property {string} url
266 * @property {boolean} attached
267 */
268
269module.exports = { Browser, TaskQueue, Target };