Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Error uploading file page.setContent: Navigation failed because page crashed! #34169

Open
Himanshu-Agg12 opened this issue Dec 30, 2024 · 3 comments

Comments

@Himanshu-Agg12
Copy link

Version

1.24.0

Steps to reproduce

import { chromium, Browser } from 'playwright';
import { MyLoggerService } from 'src/logger.service';  
@Injectable()
export class PlaywrightService implements OnModuleInit, OnModuleDestroy {
    private browserInstance: Browser | null = null;
    private retryAttempts = 3;

    constructor(
        private readonly loggerService: MyLoggerService,
    ) {}

    async onModuleInit() {
        await this.initializeBrowser();
    }

  
    async onModuleDestroy() {
        await this.closeBrowser();
    }

    async initializeBrowser() {
        try {
            if (!this.browserInstance || !this.browserInstance.isConnected()) {
                const launchOptions: any = {
                    headless: true,
                    args: ['--no-sandbox', '--disable-setuid-sandbox','--disable-dev-shm-usage', '--disable-gpu'],
                };
    
             
                if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'sandbox') {
                    launchOptions.executablePath = process.env.CHROMIUM_EXECUTABLE_PATH;
                }
    
                this.browserInstance = await chromium.launch(launchOptions);
                // Add event listener for disconnection
                this.browserInstance.on('disconnected', () => {
                    this.loggerService.error(
                        'Browser disconnected unexpectedly',
                        null,
                        'PlaywrightService'
                    );
                    this.browserInstance = null;
                });
                this.loggerService.log('Browser instance created', 'PlaywrightService');
            }
        } catch (error) {
            this.loggerService.error('Error occurred while initializing browser', error, 'PlaywrightService');
            throw error;
        }
    }

    
    async closeBrowser() {
        if (this.browserInstance) {
            try {
                await this.browserInstance.close();
                this.browserInstance = null;
                this.loggerService.log('Browser instance closed', 'PlaywrightService');
            } catch (error) {
                this.loggerService.error('Error occurred while closing browser', error, 'PlaywrightService');
            }
        }
    }

    async getPdfBufferData(htmlContent: string): Promise<Buffer> {
        let attempt = 0;
        
        while (attempt < this.retryAttempts) {
            try {
                // Check if browser is connected
                if (!this.browserInstance || !this.browserInstance?.isConnected()) {
                    await this.initializeBrowser();
                }

                if (!this.browserInstance || !this.browserInstance?.isConnected()) {
                    throw new Error('Failed to initialize browser');
                }

                const context = await this.browserInstance.newContext();
                const page = await context.newPage();
                
                try {
                    this.loggerService.log('Setting content for page', 'PlaywrightService');
                    await page.setContent(htmlContent, { waitUntil: 'networkidle' });
                    this.loggerService.log('Content set for page', 'PlaywrightService');
                    page.on('crash', () => {
                        this.loggerService.error(
                            'Page crashed unexpectedly',
                            null,
                            'PlaywrightService'
                        );
                        this.browserInstance = null;
                    });
                    this.loggerService.log('Generating PDF', 'PlaywrightService');
                    const pdfBuffer = await page.pdf({
                        format: 'A4',
                        printBackground: true,
                        scale: 0.8
                    });
                    this.loggerService.log('PDF generated', 'PlaywrightService');
                    return pdfBuffer;
                } finally {
                    await page.close();
                    await context.close();
                }
            } catch (error) {
                attempt++;
                this.loggerService.error(
                    `Error generating PDF for HTML content (attempt ${attempt}/${this.retryAttempts})`,
                    error,
                    'PlaywrightService'
                );
                
                if (attempt === this.retryAttempts) {
                    throw error;
                }
                
                // Wait before retrying
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }
    }
}

Expected behavior

I should get the pdf buffer.

Actual behavior

It is throwing error as "Error uploading file page.setContent: Navigation failed because page crashed!"
Image

Additional context

No response

Environment

.
@yury-s
Copy link
Member

yury-s commented Dec 30, 2024

Please extract relevant parts into a standalone repro that we could run locally to see the problem. Also make sure you run it with the latest Playwright version.

@Himanshu-Agg12
Copy link
Author

Please extract relevant parts into a standalone repro that we could run locally to see the problem. Also make sure you run it with the latest Playwright version.

The complete file is needed to reproduce. Once we try generating pdf from HTML, it start breaking

@dgozman
Copy link
Contributor

dgozman commented Jan 2, 2025

@Himanshu-Agg12 The error message says that the browser crashes trying to load your htmlContent. The best you can do is to update Playwright to a newer version where the bundled browser has this crash already fixed.

If you can update to the latest v1.49 Playwright version, and the issue still reproduces, then share your htmlContent with us, so we can look at the crash. Without reproducing the crash ourselves with the exact htmlContent, we won't be able to help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants