feat(workers): create workers from service workers and shared workers (#4397)

This allows users to easily evaluate javascript inside service workers and shared workers by creating a Worker object for them.
This commit is contained in:
Joel Einbinder
2019-05-09 20:29:18 -04:00
committed by Andrey Lushnikov
parent ef24c69c62
commit 1516e0df21
3 changed files with 51 additions and 4 deletions

View File

@@ -16,6 +16,8 @@
const {Events} = require('./Events');
const {Page} = require('./Page');
const {Worker} = require('./Worker');
const {Connection} = require('./Connection');
class Target {
/**
@@ -36,6 +38,8 @@ class Target {
this._screenshotTaskQueue = screenshotTaskQueue;
/** @type {?Promise<!Puppeteer.Page>} */
this._pagePromise = null;
/** @type {?Promise<!Worker>} */
this._workerPromise = null;
this._initializedPromise = new Promise(fulfill => this._initializedCallback = fulfill).then(async success => {
if (!success)
return false;
@@ -73,6 +77,27 @@ class Target {
return this._pagePromise;
}
/**
* @return {!Promise<?Worker>}
*/
async worker() {
if (this._targetInfo.type !== 'service_worker' && this._targetInfo.type !== 'shared_worker')
return null;
if (!this._workerPromise) {
this._workerPromise = this._sessionFactory().then(async client => {
// Top level workers have a fake page wrapping the actual worker.
const [targetAttached] = await Promise.all([
new Promise(x => client.once('Target.attachedToTarget', x)),
client.send('Target.setAutoAttach', {autoAttach: true, waitForDebuggerOnStart: false, flatten: true}),
]);
const session = Connection.fromSession(client).session(targetAttached.sessionId);
// TODO(einbinder): Make workers send their console logs.
return new Worker(session, this._targetInfo.url, () => {} /* consoleAPICalled */, () => {} /* exceptionThrown */);
});
}
return this._workerPromise;
}
/**
* @return {string}
*/
@@ -81,11 +106,11 @@ class Target {
}
/**
* @return {"page"|"background_page"|"service_worker"|"other"|"browser"}
* @return {"page"|"background_page"|"service_worker"|"shared_worker"|"other"|"browser"}
*/
type() {
const type = this._targetInfo.type;
if (type === 'page' || type === 'background_page' || type === 'service_worker' || type === 'browser')
if (type === 'page' || type === 'background_page' || type === 'service_worker' || type === 'shared_worker' || type === 'browser')
return type;
return 'other';
}