UNPKG

2.82 kBJavaScriptView Raw
1/**
2 * Copyright 2018 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 */
16const EventEmitter = require('events');
17const {helper, debugError} = require('./helper');
18const {ExecutionContext, JSHandle} = require('./ExecutionContext');
19
20class Worker extends EventEmitter {
21 /**
22 * @param {Puppeteer.CDPSession} client
23 * @param {string} url
24 * @param {function(!string, !Array<!JSHandle>)} consoleAPICalled
25 * @param {function(!Protocol.Runtime.ExceptionDetails)} exceptionThrown
26 */
27 constructor(client, url, consoleAPICalled, exceptionThrown) {
28 super();
29 this._client = client;
30 this._url = url;
31 this._executionContextPromise = new Promise(x => this._executionContextCallback = x);
32 /** @type {function(!Protocol.Runtime.RemoteObject):!JSHandle} */
33 let jsHandleFactory;
34 this._client.once('Runtime.executionContextCreated', async event => {
35 jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject);
36 const executionContext = new ExecutionContext(client, event.context, jsHandleFactory, null);
37 this._executionContextCallback(executionContext);
38 });
39 // This might fail if the target is closed before we recieve all execution contexts.
40 this._client.send('Runtime.enable', {}).catch(debugError);
41
42 this._client.on('Runtime.consoleAPICalled', event => consoleAPICalled(event.type, event.args.map(jsHandleFactory)));
43 this._client.on('Runtime.exceptionThrown', exception => exceptionThrown(exception.exceptionDetails));
44 }
45
46 /**
47 * @return {string}
48 */
49 url() {
50 return this._url;
51 }
52
53 /**
54 * @return {!Promise<ExecutionContext>}
55 */
56 async executionContext() {
57 return this._executionContextPromise;
58 }
59
60 /**
61 * @param {function()|string} pageFunction
62 * @param {!Array<*>} args
63 * @return {!Promise<*>}
64 */
65 async evaluate(pageFunction, ...args) {
66 return (await this._executionContextPromise).evaluate(pageFunction, ...args);
67 }
68
69 /**
70 * @param {function()|string} pageFunction
71 * @param {!Array<*>} args
72 * @return {!Promise<!JSHandle>}
73 */
74 async evaluateHandle(pageFunction, ...args) {
75 return (await this._executionContextPromise).evaluateHandle(pageFunction, ...args);
76 }
77}
78
79module.exports = Worker;
80helper.tracePublicAPI(Worker);