Skip to content

Commit

Permalink
refactor: introduce an internal PageTarget subclass (#10167)
Browse files Browse the repository at this point in the history
  • Loading branch information
OrKoN committed May 12, 2023
1 parent c05a94a commit f342a12
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 84 deletions.
20 changes: 10 additions & 10 deletions docs/api/puppeteer.target.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ The constructor for this class is marked as internal. Third-party code should no

## Methods

| Method | Modifiers | Description |
| ------------------------------------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| [browser()](./puppeteer.target.browser.md) | | Get the browser the target belongs to. |
| [browserContext()](./puppeteer.target.browsercontext.md) | | Get the browser context the target belongs to. |
| [createCDPSession()](./puppeteer.target.createcdpsession.md) | | Creates a Chrome Devtools Protocol session attached to the target. |
| [opener()](./puppeteer.target.opener.md) | | Get the target that opened this target. Top-level targets return <code>null</code>. |
| [page()](./puppeteer.target.page.md) | | If the target is not of type <code>&quot;page&quot;</code> or <code>&quot;background_page&quot;</code>, returns <code>null</code>. |
| [type()](./puppeteer.target.type.md) | | Identifies what kind of target this is. |
| [url()](./puppeteer.target.url.md) | | |
| [worker()](./puppeteer.target.worker.md) | | If the target is not of type <code>&quot;service_worker&quot;</code> or <code>&quot;shared_worker&quot;</code>, returns <code>null</code>. |
| Method | Modifiers | Description |
| ------------------------------------------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [browser()](./puppeteer.target.browser.md) | | Get the browser the target belongs to. |
| [browserContext()](./puppeteer.target.browsercontext.md) | | Get the browser context the target belongs to. |
| [createCDPSession()](./puppeteer.target.createcdpsession.md) | | Creates a Chrome Devtools Protocol session attached to the target. |
| [opener()](./puppeteer.target.opener.md) | | Get the target that opened this target. Top-level targets return <code>null</code>. |
| [page()](./puppeteer.target.page.md) | | If the target is not of type <code>&quot;page&quot;</code>, <code>&quot;webview&quot;</code> or <code>&quot;background_page&quot;</code>, returns <code>null</code>. |
| [type()](./puppeteer.target.type.md) | | Identifies what kind of target this is. |
| [url()](./puppeteer.target.url.md) | | |
| [worker()](./puppeteer.target.worker.md) | | If the target is not of type <code>&quot;service_worker&quot;</code> or <code>&quot;shared_worker&quot;</code>, returns <code>null</code>. |
2 changes: 1 addition & 1 deletion docs/api/puppeteer.target.page.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ sidebar_label: Target.page

# Target.page() method

If the target is not of type `"page"` or `"background_page"`, returns `null`.
If the target is not of type `"page"`, `"webview"` or `"background_page"`, returns `null`.

#### Signature:

Expand Down
25 changes: 19 additions & 6 deletions packages/puppeteer-core/src/common/Browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {ChromeTargetManager} from './ChromeTargetManager.js';
import {CDPSession, Connection, ConnectionEmittedEvents} from './Connection.js';
import {FirefoxTargetManager} from './FirefoxTargetManager.js';
import {Viewport} from './PuppeteerViewport.js';
import {Target} from './Target.js';
import {PageTarget, Target} from './Target.js';
import {TargetManager, TargetManagerEmittedEvents} from './TargetManager.js';
import {TaskQueue} from './TaskQueue.js';
import {waitWithTimeout} from './util.js';
Expand Down Expand Up @@ -318,6 +318,23 @@ export class CDPBrowser extends BrowserBase {
throw new Error('Missing browser context');
}

if (this.#isPageTargetCallback(targetInfo)) {
return new PageTarget(
targetInfo,
session,
context,
this.#targetManager,
(isAutoAttachEmulated: boolean) => {
return this.#connection._createSession(
targetInfo,
isAutoAttachEmulated
);
},
this.#ignoreHTTPSErrors,
this.#defaultViewport ?? null,
this.#screenshotTaskQueue
);
}
return new Target(
targetInfo,
session,
Expand All @@ -328,11 +345,7 @@ export class CDPBrowser extends BrowserBase {
targetInfo,
isAutoAttachEmulated
);
},
this.#ignoreHTTPSErrors,
this.#defaultViewport ?? null,
this.#screenshotTaskQueue,
this.#isPageTargetCallback
}
);
};

Expand Down
189 changes: 122 additions & 67 deletions packages/puppeteer-core/src/common/Target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import {Protocol} from 'devtools-protocol';

import type {Browser, IsPageTargetCallback} from '../api/Browser.js';
import type {Browser} from '../api/Browser.js';
import type {BrowserContext} from '../api/BrowserContext.js';
import {Page, PageEmittedEvents} from '../api/Page.js';

Expand All @@ -25,6 +25,7 @@ import {CDPPage} from './Page.js';
import {Viewport} from './PuppeteerViewport.js';
import {TargetManager} from './TargetManager.js';
import {TaskQueue} from './TaskQueue.js';
import {debugError} from './util.js';
import {WebWorker} from './WebWorker.js';

/**
Expand All @@ -40,11 +41,7 @@ export class Target {
#session?: CDPSession;
#targetInfo: Protocol.Target.TargetInfo;
#sessionFactory: (isAutoAttachEmulated: boolean) => Promise<CDPSession>;
#ignoreHTTPSErrors: boolean;
#defaultViewport?: Viewport;
#pagePromise?: Promise<Page>;
#workerPromise?: Promise<WebWorker>;
#screenshotTaskQueue: TaskQueue;

/**
* @internal
Expand All @@ -65,15 +62,11 @@ export class Target {
/**
* @internal
*/
_isInitialized: boolean;
_isInitialized = false;
/**
* @internal
*/
_targetId: string;
/**
* @internal
*/
_isPageTargetCallback: IsPageTargetCallback;

#targetManager: TargetManager;

Expand All @@ -85,49 +78,21 @@ export class Target {
session: CDPSession | undefined,
browserContext: BrowserContext,
targetManager: TargetManager,
sessionFactory: (isAutoAttachEmulated: boolean) => Promise<CDPSession>,
ignoreHTTPSErrors: boolean,
defaultViewport: Viewport | null,
screenshotTaskQueue: TaskQueue,
isPageTargetCallback: IsPageTargetCallback
sessionFactory: (isAutoAttachEmulated: boolean) => Promise<CDPSession>
) {
this.#session = session;
this.#targetManager = targetManager;
this.#targetInfo = targetInfo;
this.#browserContext = browserContext;
this._targetId = targetInfo.targetId;
this.#sessionFactory = sessionFactory;
this.#ignoreHTTPSErrors = ignoreHTTPSErrors;
this.#defaultViewport = defaultViewport ?? undefined;
this.#screenshotTaskQueue = screenshotTaskQueue;
this._isPageTargetCallback = isPageTargetCallback;
this._initializedPromise = new Promise<boolean>(fulfill => {
return (this._initializedCallback = fulfill);
}).then(async success => {
if (!success) {
return false;
}
const opener = this.opener();
if (!opener || !opener.#pagePromise || this.type() !== 'page') {
return true;
}
const openerPage = await opener.#pagePromise;
if (!openerPage.listenerCount(PageEmittedEvents.Popup)) {
return true;
}
const popupPage = await this.page();
openerPage.emit(PageEmittedEvents.Popup, popupPage);
return true;
});
this._isClosedPromise = new Promise<void>(fulfill => {
return (this._closedCallback = fulfill);
});
this._isInitialized =
!this._isPageTargetCallback(this.#targetInfo) ||
this.#targetInfo.url !== '';
if (this._isInitialized) {
this._initializedCallback(true);
}
this._initialize();
}

/**
Expand All @@ -137,6 +102,15 @@ export class Target {
return this.#session;
}

/**
* @internal
*/
protected _sessionFactory(): (
isAutoAttachEmulated: boolean
) => Promise<CDPSession> {
return this.#sessionFactory;
}

/**
* Creates a Chrome Devtools Protocol session attached to the target.
*/
Expand All @@ -158,28 +132,6 @@ export class Target {
return this.#targetInfo;
}

/**
* If the target is not of type `"page"` or `"background_page"`, returns `null`.
*/
async page(): Promise<Page | null> {
if (this._isPageTargetCallback(this.#targetInfo) && !this.#pagePromise) {
this.#pagePromise = (
this.#session
? Promise.resolve(this.#session)
: this.#sessionFactory(true)
).then(client => {
return CDPPage._create(
client,
this,
this.#ignoreHTTPSErrors,
this.#defaultViewport ?? null,
this.#screenshotTaskQueue
);
});
}
return (await this.#pagePromise) ?? null;
}

/**
* If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.
*/
Expand Down Expand Up @@ -271,15 +223,118 @@ export class Target {
*/
_targetInfoChanged(targetInfo: Protocol.Target.TargetInfo): void {
this.#targetInfo = targetInfo;
this._checkIfInitialized();
}

if (
!this._isInitialized &&
(!this._isPageTargetCallback(this.#targetInfo) ||
this.#targetInfo.url !== '')
) {
/**
* @internal
*/
protected _initialize(): void {
// TODO: refactor to deferred promises.
this._isInitialized = true;
if (this._isInitialized) {
this._initializedCallback(true);
}
}

/**
* @internal
*/
protected _checkIfInitialized(): void {
if (!this._isInitialized) {
this._isInitialized = true;
this._initializedCallback(true);
return;
}
}

/**
* If the target is not of type `"page"`, `"webview"` or `"background_page"`,
* returns `null`.
*/
async page(): Promise<Page | null> {
return null;
}
}

/**
* @internal
*/
export class PageTarget extends Target {
#defaultViewport?: Viewport;
protected pagePromise?: Promise<Page>;
#screenshotTaskQueue: TaskQueue;
#ignoreHTTPSErrors: boolean;

/**
* @internal
*/
constructor(
targetInfo: Protocol.Target.TargetInfo,
session: CDPSession | undefined,
browserContext: BrowserContext,
targetManager: TargetManager,
sessionFactory: (isAutoAttachEmulated: boolean) => Promise<CDPSession>,
ignoreHTTPSErrors: boolean,
defaultViewport: Viewport | null,
screenshotTaskQueue: TaskQueue
) {
super(targetInfo, session, browserContext, targetManager, sessionFactory);
this.#ignoreHTTPSErrors = ignoreHTTPSErrors;
this.#defaultViewport = defaultViewport ?? undefined;
this.#screenshotTaskQueue = screenshotTaskQueue;
}

protected override _initialize(): void {
this._initializedPromise
.then(async success => {
if (!success) {
return false;
}
const opener = this.opener();
if (!(opener instanceof PageTarget)) {
return true;
}
if (!opener || !opener.pagePromise || this.type() !== 'page') {
return true;
}
const openerPage = await opener.pagePromise;
if (!openerPage.listenerCount(PageEmittedEvents.Popup)) {
return true;
}
const popupPage = await this.page();
openerPage.emit(PageEmittedEvents.Popup, popupPage);
return true;
})
.catch(debugError);
this._checkIfInitialized();
}

override async page(): Promise<Page | null> {
if (!this.pagePromise) {
const session = this._session();
this.pagePromise = (
session ? Promise.resolve(session) : this._sessionFactory()(true)
).then(client => {
return CDPPage._create(
client,
this,
this.#ignoreHTTPSErrors,
this.#defaultViewport ?? null,
this.#screenshotTaskQueue
);
});
}
return (await this.pagePromise) ?? null;
}

override _checkIfInitialized(): void {
if (this._isInitialized) {
return;
}
this._isInitialized = this._getTargetInfo().url !== '';
if (this._isInitialized) {
this._initializedCallback(true);
}
}
}

0 comments on commit f342a12

Please sign in to comment.