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]: Navigation failed because browser has disconnected! #12395

Closed
2 tasks
sajiiii opened this issue May 6, 2024 · 2 comments
Closed
2 tasks

[Bug]: Navigation failed because browser has disconnected! #12395

sajiiii opened this issue May 6, 2024 · 2 comments

Comments

@sajiiii
Copy link

sajiiii commented May 6, 2024

Minimal, reproducible example

//App Module
import { Injectable } from "@nestjs/common";
import { ConfigModule } from '@nestjs/config';

//App Module
import { CertificateDetailsService } from "src/modules/certificate_details/certificate_details.service";
// import { constantData } from '../common/constant/certificate_constant';

//Thirdy Party Module
import * as fs from 'fs';
import aws_sdk from 'aws-sdk';
import puppeteer from 'puppeteer-core';
import chromium from '@sparticuz/chromium';

const hbs = require('handlebars');
ConfigModule.forRoot();


@Injectable()
export class GeneratePdf {
  data = {};
  constructor(
    private readonly certificatedetailsservice: CertificateDetailsService
  ) { }

  /**
   * generate pdf and upload
   */
  async getDetails(dataFinal, certificateDet) {
    try {
      return new Promise(async (resolve, reject) => {
        this.data = dataFinal;
        let url = await this.uploadToS3(certificateDet);
        resolve(url)
      })
      // this.data = dataFinal;
      // this.uploadToS3(certificateDet)
    } catch (e) {
      throw e
    }
  }

  /**
   * get the certificate html and attach hbs and compile
   * @returns HTML string
   */
  async injectDataToPdf() {
    try {
      const html = fs.readFileSync(__dirname + '/ecert.hbs', 'utf-8');
      const pdf_html = hbs.compile(html)(this.data);
      return pdf_html;
    } catch (e) {
      throw e
    }
  }

  /**
   * create and upload the pdf and create new record into certificate_details table
   */
  async uploadToS3(certificateDet) {
    try {
      return new Promise(async (resolve, reject) => {
        console.log('PDF uploaded successfully:');
        const s3 = new aws_sdk.S3({
          region: "ap-south-1",
          // credentials,
        });
        console.log('PDF uploaded successfully:2');
        const browser = await puppeteer.launch({
          args: chromium.args,
          defaultViewport: chromium.defaultViewport,
          executablePath: await chromium.executablePath(),
          headless: chromium.headless,
          ignoreHTTPSErrors: true,
        });
        console.log('PDF uploaded successfully:3');
        const page = await browser.newPage();
        const content = await this.injectDataToPdf();
        await page.setContent(content, { waitUntil: "networkidle2", timeout: 60000 }); // Increase timeout to 60 seconds
        await page.waitForSelector('img');
        const pdfBuffer = await page.pdf({
          format: 'A4', printBackground: true,
          headerTemplate: "<div>header</div>",
          footerTemplate: "<div>footer</div>"
        });
        const currentTimestampSeconds = Math.floor(Date.now() / 1000);
        const uploadParams = {
          Bucket: process.env.ECERTIFICATE_BUCKET,
          Key: this.data["certificate_no"] + "_" + currentTimestampSeconds + ".pdf",
          Body: pdfBuffer,
          ACL: 'public-read' //enable it for stage
        };
        s3.upload(uploadParams, async (err, data) => {
          if (err) {
            console.error('Error uploading PDF to S3:', err);
          }
          else {
            console.log('PDF uploaded successfully:', data.Location);
            await this.certificatedetailsservice.createRecord(certificateDet, uploadParams["Key"], this.data);
            this.flushData();
          }
          browser.close();
          resolve("pdf generated")
        });
      });
    } catch (error) {
      console.error('Error generating PDF:', error);
    }
  }
  flushData() {
    this.data = {};
  }

}

Error string

Navigation failed because browser has disconnected!

Bug behavior

  • Flaky
  • PDF

Background

No response

Expectation

it should not show the error

Reality

it is showing this error
Screenshot 2024-05-06 at 2 39 24 PM

Puppeteer configuration file (if used)

No response

Puppeteer version

 "puppeteer": "^19.11.1",

Node version

18

Package manager

npm

Package manager version

10.2.3

Operating system

Linux

@sajiiii sajiiii added the bug label May 6, 2024
Copy link

github-actions bot commented May 6, 2024

This issue has an invalid Node.js version: 18. Versions must follow SemVer formatting. Please update the form with a valid version.


Analyzer run

@OrKoN
Copy link
Collaborator

OrKoN commented May 6, 2024

Is this on AWS Lambda? This indicates that the browser crashes during navigation. Please report the issue to @sparticuz/chromium as those are not builds we support. If you can re-produce it with bundles Chrome for Testing binaries outside of Lambda, please provide a minimal reproducible example.

@OrKoN OrKoN closed this as not planned Won't fix, can't repro, duplicate, stale May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants