UNPKG

2.53 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(!Protocol.Log.entryAddedPayload)} logEntryAdded
25 */
26 constructor(client, url, logEntryAdded) {
27 super();
28 this._client = client;
29 this._url = url;
30 this._executionContextPromise = new Promise(x => this._executionContextCallback = x);
31 this._client.once('Runtime.executionContextCreated', async event => {
32 const jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject);
33 const executionContext = new ExecutionContext(client, event.context, jsHandleFactory, null);
34 this._executionContextCallback(executionContext);
35 });
36 // This might fail if the target is closed before we recieve all execution contexts.
37 this._client.send('Runtime.enable', {}).catch(debugError);
38
39 this._client.on('Log.entryAdded', logEntryAdded);
40 this._client.send('Log.enable', {}).catch(debugError);
41 }
42
43 /**
44 * @return {string}
45 */
46 url() {
47 return this._url;
48 }
49
50 /**
51 * @return {!Promise<ExecutionContext>}
52 */
53 async executionContext() {
54 return this._executionContextPromise;
55 }
56
57 /**
58 * @param {function()|string} pageFunction
59 * @param {!Array<*>} args
60 * @return {!Promise<*>}
61 */
62 async evaluate(pageFunction, ...args) {
63 return (await this._executionContextPromise).evaluate(pageFunction, ...args);
64 }
65
66 /**
67 * @param {function()|string} pageFunction
68 * @param {!Array<*>} args
69 * @return {!Promise<!JSHandle>}
70 */
71 async evaluateHandle(pageFunction, ...args) {
72 return (await this._executionContextPromise).evaluateHandle(pageFunction, ...args);
73 }
74}
75
76module.exports = Worker;
77helper.tracePublicAPI(Worker);