@@ -9,6 +9,11 @@ import type {Browser, HTTPRequest, Page} from 'puppeteer-core';
99export class PageCollector < T > {
1010 #browser: Browser ;
1111 #initializer: ( page : Page , collector : ( item : T ) => void ) => void ;
12+ /**
13+ * The Array in this map should only be set once
14+ * As we use the reference to it.
15+ * Use methods that manipulate the array in place.
16+ */
1217 protected storage = new WeakMap < Page , T [ ] > ( ) ;
1318
1419 constructor (
@@ -44,6 +49,9 @@ export class PageCollector<T> {
4449 return ;
4550 }
4651
52+ const stored : T [ ] = [ ] ;
53+ this . storage . set ( page , stored ) ;
54+
4755 page . on ( 'framenavigated' , frame => {
4856 // Only reset the storage on main frame navigation
4957 if ( frame !== page . mainFrame ( ) ) {
@@ -52,16 +60,16 @@ export class PageCollector<T> {
5260 this . cleanup ( page ) ;
5361 } ) ;
5462 this . #initializer( page , value => {
55- const stored = this . storage . get ( page ) ?? [ ] ;
5663 stored . push ( value ) ;
57- this . storage . set ( page , stored ) ;
5864 } ) ;
5965 }
6066
6167 protected cleanup ( page : Page ) {
62- const collection = this . storage . get ( page ) ?? [ ] ;
63- // Keep the reference alive
64- collection . length = 0 ;
68+ const collection = this . storage . get ( page ) ;
69+ if ( collection ) {
70+ // Keep the reference alive
71+ collection . length = 0 ;
72+ }
6573 }
6674
6775 getData ( page : Page ) : T [ ] {
@@ -72,13 +80,17 @@ export class PageCollector<T> {
7280export class NetworkCollector extends PageCollector < HTTPRequest > {
7381 override cleanup ( page : Page ) {
7482 const requests = this . storage . get ( page ) ?? [ ] ;
83+ if ( ! requests ) {
84+ return ;
85+ }
7586 const lastRequestIdx = requests . findLastIndex ( request => {
7687 return request . frame ( ) === page . mainFrame ( )
7788 ? request . isNavigationRequest ( )
7889 : false ;
7990 } ) ;
8091 // Keep all requests since the last navigation request including that
8192 // navigation request itself.
82- this . storage . set ( page , requests . slice ( Math . max ( lastRequestIdx , 0 ) ) ) ;
93+ // Keep the reference
94+ requests . splice ( 0 , Math . max ( lastRequestIdx , 0 ) ) ;
8395 }
8496}
0 commit comments