@@ -40,7 +40,7 @@ export class Tab extends EventEmitter<TabEventsMap> {
4040 #isLoading = false ;
4141 #reloadAbortController: AbortController | null = null ;
4242
43- #scriptsOnCreate: string [ ] = [ disableWebdriver , visibilityScript ] ;
43+ #scriptsOnCreate: string [ ] = [ disableWebdriver ] ;
4444 #scriptsOnLoad: string [ ] = [ ] ;
4545
4646 constructor ( page : Page , options : TabOptions ) {
@@ -58,20 +58,26 @@ export class Tab extends EventEmitter<TabEventsMap> {
5858 this . #keyboard = new Keyboard ( page , this . #tabDialog, options . envInfo ) ;
5959 this . #mouse = new Mouse ( page , this . #tabDialog) ;
6060
61- this . #setupVisibilityTracking( ) ;
62- this . #executeScriptsOnCreate( ) ;
63-
64- // Set user agent if provided
65- if ( options . userAgentInfo ) {
66- this . #pptrPage. setUserAgent ( options . userAgentInfo ) ;
67- }
68-
6961 // page events: https://pptr.dev/api/puppeteer.pageevent
7062 this . #pptrPage. on ( 'domcontentloaded' , this . #dclHandler) ;
7163 this . #pptrPage. on ( 'load' , this . #loadHandler) ;
7264 this . #pptrPage. on ( 'framenavigated' , this . #frameNavigatedHandler) ;
7365 }
7466
67+ async init ( ) {
68+ // Only setup visibility tracking if visibility script is injected
69+ if ( this . #options. injectVisibilityScript ) {
70+ this . #scriptsOnCreate. push ( visibilityScript ) ;
71+ await this . #setupVisibilityTracking( ) ;
72+ }
73+
74+ await this . #executeScriptsOnCreate( ) ;
75+
76+ if ( this . #options. userAgentInfo ) {
77+ await this . #pptrPage. setUserAgent ( this . #options. userAgentInfo ) ;
78+ }
79+ }
80+
7581 // #region meta info
7682
7783 get tabId ( ) {
@@ -464,8 +470,10 @@ export class Tab extends EventEmitter<TabEventsMap> {
464470 async #executeScriptsOnCreate( ) {
465471 try {
466472 const script = iife ( this . #scriptsOnCreate. join ( '\n' ) ) ;
467- await this . #pptrPage. evaluateOnNewDocument ( script ) ;
468- await this . #pptrPage. evaluate ( script ) ;
473+ await Promise . race ( [
474+ this . #pptrPage. evaluateOnNewDocument ( script ) ,
475+ this . #pptrPage. evaluate ( script ) ,
476+ ] ) ;
469477 } catch ( error ) {
470478 console . warn ( 'Failed to execute script on create:' , error ) ;
471479 }
0 commit comments