diff --git a/packages/puppeteer-core/src/common/Browser.ts b/packages/puppeteer-core/src/common/Browser.ts index 2e18acd8ff5..0687335718b 100644 --- a/packages/puppeteer-core/src/common/Browser.ts +++ b/packages/puppeteer-core/src/common/Browser.ts @@ -374,22 +374,11 @@ export class CDPBrowser extends BrowserBase { } }; - #onTargetChanged = ({ - target, - targetInfo, - }: { - target: Target; - targetInfo: Protocol.Target.TargetInfo; - }): void => { - const previousURL = target.url(); - const wasInitialized = target._isInitialized; - target._targetInfoChanged(targetInfo); - if (wasInitialized && previousURL !== target.url()) { - this.emit(BrowserEmittedEvents.TargetChanged, target); - target - .browserContext() - .emit(BrowserContextEmittedEvents.TargetChanged, target); - } + #onTargetChanged = ({target}: {target: Target}): void => { + this.emit(BrowserEmittedEvents.TargetChanged, target); + target + .browserContext() + .emit(BrowserContextEmittedEvents.TargetChanged, target); }; #onTargetDiscovered = (targetInfo: Protocol.Target.TargetInfo): void => { diff --git a/packages/puppeteer-core/src/common/ChromeTargetManager.ts b/packages/puppeteer-core/src/common/ChromeTargetManager.ts index 58c8353aadb..153611b5e1c 100644 --- a/packages/puppeteer-core/src/common/ChromeTargetManager.ts +++ b/packages/puppeteer-core/src/common/ChromeTargetManager.ts @@ -263,10 +263,21 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager { const target = this.#attachedTargetsByTargetId.get( event.targetInfo.targetId ); - this.emit(TargetManagerEmittedEvents.TargetChanged, { - target: target!, - targetInfo: event.targetInfo, - }); + if (!target) { + return; + } + const previousURL = target.url(); + const wasInitialized = target._isInitialized; + + target._targetInfoChanged(event.targetInfo); + + if (wasInitialized && previousURL !== target.url()) { + this.emit(TargetManagerEmittedEvents.TargetChanged, { + target: target, + wasInitialized, + previousURL, + }); + } }; #onAttachedToTarget = async ( diff --git a/packages/puppeteer-core/src/common/TargetManager.ts b/packages/puppeteer-core/src/common/TargetManager.ts index 4f69b72ba98..3f0c6e3399f 100644 --- a/packages/puppeteer-core/src/common/TargetManager.ts +++ b/packages/puppeteer-core/src/common/TargetManager.ts @@ -68,5 +68,8 @@ export const enum TargetManagerEmittedEvents { TargetDiscovered = 'targetDiscovered', TargetAvailable = 'targetAvailable', TargetGone = 'targetGone', + /** + * Emitted after a target has been initialized and whenever its URL changes. + */ TargetChanged = 'targetChanged', }