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

TimeoutError: Timed out after 30000 ms while trying to connect to Chrome! #4796

Closed
knandraina opened this issue Aug 2, 2019 · 124 comments · Fixed by #6011
Closed

TimeoutError: Timed out after 30000 ms while trying to connect to Chrome! #4796

knandraina opened this issue Aug 2, 2019 · 124 comments · Fixed by #6011

Comments

@knandraina
Copy link

knandraina commented Aug 2, 2019

Hello

I try to implement/deploy puppeteer on Google Cloud but I have some issues. What I don't understand, it worked well 2 days ago.
Since then, I have this error:

TimeoutError: Timed out after 30000 ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r674921 at Timeout.onTimeout

I ran this command and everything seems fine : DEBUG=* node app.js

Version puppeteer : ^1.19.0
Version Node : v8.11.3

And here the code:

`async function main_screenshot(project_id) {
try {
const browser = await puppeteer.launch({
headless: true,
args: ["--window-size=1440,1000", "--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"]
});
// const browser = await puppeteer.launch({dumpio: true});
const page = await browser.newPage()
page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36')
page.setViewport({ width: 1440, height: 721 })
console.log('entering in screenshot zone')
page.setDefaultNavigationTimeout(30000)
await page.goto('https://app.slack.com/client/TLW4JE7AA/CLTFQT9GC')
await page.waitFor(3000)
await page.type('#email', process.env.SLACK_EMAIL)
await page.type('#password', process.env.SLACK_PWD)
await page.waitFor(3000)
await page.click('#signin_btn')
console.log('credentials done')
await page.waitFor(3000)
console.log('so?')
await page.goto('https://app.slack.com/client/TLW4JE7AA/CLTFQT9GC')
await page.waitFor(3000)
console.log('connected to the right environment')
const div = await page.$$('.c-message.c-message--light')
var nuwwmber_loop= 0
for (var i = div.length ; i > 0; i--) {
var text = await (await div[i - 1].getProperty('textContent')).jsonValue();

  if(text.includes(project_id)) {
    number_loop = i
    break
  }
}
// const text = await (await div.getProperty('textContent')).jsonValue();


 const shotResult = await div[number_loop-1].screenshot();
console.log(shotResult)
cloudinaryOptions = {
  public_id: `${project_id}`
}

const results = await uploadToCloudinary(shotResult, cloudinaryOptions)
console.log(results)
browser.close()
return results

} catch (e) {
console.log(e)
}
}`

@knandraina
Copy link
Author

Quick update I downloaded the previous code, no really big changes...

@michaelpaco
Copy link

Did you get it to work? Same problem here ):

@knandraina
Copy link
Author

not yet :/

@ghost
Copy link

ghost commented Aug 7, 2019

Same here. Cannot get it to work

@Fredericco72
Copy link

I also have this issue,

Node v10.15.3
Puppeteer v1.19.0

@knandraina
Copy link
Author

I use "puppeteer-core": "^1.19.0",

when I use headless: false, it can work.
But when I use headless:true, it will be TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded

Yes, but it's a different kind of error :)

@suwilliam
Copy link

bumping because I also get this error and can't seem to find a solution. I get both TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded and TimeoutError while connecting to Chrome :(

@sparker-sagrad
Copy link

sparker-sagrad commented Sep 13, 2019

I'm getting the similar error:

(node:11400) UnhandledPromiseRejectionWarning: TimeoutError: Timed out after 40000 ms whil e trying to connect to Chrome! The only Chrome revision guaranteed to work is r686378 at Timeout.onTimeout (H:\node_modules\puppeteer\lib\Launcher.js:359:14) at ontimeout (timers.js:436:11) at tryOnTimeout (timers.js:300:5) at listOnTimeout (timers.js:263:5) at Timer.processTimers (timers.js:223:10) (node:11400) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error ori ginated either by throwing inside of an async function without a catch block, or by reject ing a promise which was not handled with .catch(). (rejection id: 1) (node:11400) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process wi th a non-zero exit code.

I've tried numerous 'fixes' and nothing seems to work.

Node v10.16.3
Puppeteer v1.20 (edit)

@bruriah1999
Copy link

Having the same problem was anybody able to fix this?

@tbadlov
Copy link

tbadlov commented Sep 26, 2019

If it helps anyone my issue with was due to the usage of Puppeteer in Google Cloud Function and have it running in the background. I changed the function to respond only after Puppeteer is done and it worked just fine.

@bruriah1999
Copy link

If it helps anyone my issue with was due to the usage of Puppeteer in Google Cloud Function and have it running in the background. I changed the function to respond only after Puppeteer is done and it worked just fine.

That's exactly my problem. What exactly do you mean by changing it to respond only after Puppeteer is done?

@tbadlov
Copy link

tbadlov commented Sep 26, 2019

@bruriah1999 your entry function will have a response call. Once invoked the functions technically terminated which means all other tasks are considered background tasks and won’t execute.

Check the Function Execution Timeline in this article https://cloud.google.com/functions/docs/concepts/exec

@rodrigoreal
Copy link

@tbadlov thank you man, you saved my day, i was struggling here for hours.

@anurasin
Copy link

I also faced the same problem. it got fixed on upgrading to the latest package version.
"puppeteer": "^2.0.0",

@jjmontgo
Copy link

I'm using the latest puppeteer version (2.0.0) and receiving this error.

@tasoss
Copy link

tasoss commented Feb 13, 2020

Unfortunately i'm having this issue with 2.1.1
Maybe something that could help is that i'm running it like
ip netns exec bet365 node foobar
Without using the namespace it's working as expected...

@erv2
Copy link

erv2 commented Apr 13, 2020

I had the same problem.

I noticed that if you deploy it using the PUB/SUB trigger, this would happen. If you use HTTP as trigger instead, it runs just fine.

node.js 10 (beta)
"puppeteer": "^2.1.1",
"puppeteer-extra": "^3.1.9",

@FelipeLujan
Copy link

I'm having this issue with "puppeteer": "^3.0.1" happens randomly after several hundreds of browsers have been launched and closed previously.
I'm using GCE instances.

Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r737027 is guaranteed to work

I'm also using these extensions

 "puppeteer-extra": "^3.1.9",
   "puppeteer-extra-plugin-adblocker": "^2.11.3",
   "puppeteer-extra-plugin-anonymize-ua": "^2.2.8",
   "puppeteer-extra-plugin-block-resources": "^2.2.4",
   "puppeteer-extra-plugin-stealth": "^2.4.9"

@yadavamit9
Copy link

I am also having this issue
using puppeteer 3.1.0

Uncaught (in promise) TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r756035 is guaranteed to work.

mathiasbynens pushed a commit that referenced this issue Jun 15, 2020
Fix child process killing when the parent process SIGINTs.

If you `ctrl + c` the Puppeteer parent process, we would sometimes not properly handle killing of the child processes. This would then leave child processes behind, with running Chromium instances. This in turn could block Puppeteer from launching again and results in
cryptic errors.

Instead of using the generic `process.kill` with the process id (which for some reason is negative the pid, which I don't get), we can kill the child process directly by calling `proc.kill`.

Fixes #5729.
Fixes #4796.
Fixes #4963.
Fixes #4333.
Fixes #1825.
@PawelK2012
Copy link

@mathiasbynens #6011 meant to fix **** Exception caught: TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r756035 is guaranteed to work.. ? I updated puppeteer to v4 and still seeing this from time to time.

@p30arena
Copy link

Seeing this error
"puppeteer": "^3.0.2"

@andreabisello
Copy link

i'm obtaining this error randomly after upgrading to puppeteer 3.1
using puppeteer 2 on the same test i never got this error.

@andreabisello
Copy link

moving to puppeteer 5 even i'm not able to understand if this fix #6011 is inside puppeteer 5

@andreabisello
Copy link

andreabisello commented Jul 27, 2020

testing puppeteer 5.2.1, puppeteer 5 doesn't solve the issue.

@westonwatson
Copy link

westonwatson commented Jul 30, 2020

I'm getting this too;
TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r782078 is guaranteed to work which is weird cause we have 782078 installed???

@dcts
Copy link

dcts commented Jul 31, 2020

having the same issue. Using puppeteer 4.0.1.

@RitvikSardana
Copy link

I am having the same issue, can anyone help me with it?

I am using puppeteer in AWS EC2

@metamas
Copy link

metamas commented Jul 16, 2022

Google Cloud Functions
Node 16
Puppeteer 15.3.2

@tbadlov's suggestions solved this for me.

#4796 (comment)

If it helps anyone my issue with was due to the usage of Puppeteer in Google Cloud Function and have it running in the background. I changed the function to respond only after Puppeteer is done and it worked just fine.

#4796 (comment)

...your entry function will have a response call. Once invoked the functions technically terminated which means all other tasks are considered background tasks and won’t execute.

I changed my main function to return a promise (via return browser.close()), with an async entry point function that awaits the completion of my main function.

@saldous
Copy link

saldous commented Aug 21, 2022

I am having this issue too, on Firebase Functions. Can’t figure it out. Works fine ~20% of the time and fails all others with timeout.

@GaL3n
Copy link

GaL3n commented Sep 14, 2022

I have this issue only on Firebase pubsub scheduled function. @Greyson-Sawyer can you provide the code including the Trigger function definition ? Thanks

@jnt0009
Copy link

jnt0009 commented Sep 20, 2022

I am getting the same error using Cloud functions triggered by pubsub

Error: TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r1036745 is guaranteed to work.

Node 16
puppeteer: "17.1.3"

@paveltretyakovru
Copy link

paveltretyakovru commented Sep 28, 2022

It's magic.
I have used my simpliest script last week - it's work.
Today, no updates, but it's not working with the same issue.
It is a normal?

Node: 18.9.0
Pptr: ^18.0.5

@saldous
Copy link

saldous commented Sep 28, 2022

@paveltretyakovru are you invoking it a lot? I found Firebase Cloud was getting throttled by the website I was connecting to due to the volume of requests. For me it was ~ 5 times a second. I put the function in multiple regions and had the clients randomly pick one as a way to load balance a little to fix it.

@paveltretyakovru
Copy link

paveltretyakovru commented Sep 29, 2022

@paveltretyakovru are you invoking it a lot? I found Firebase Cloud was getting throttled by the website I was connecting to due to the volume of requests. For me it was ~ 5 times a second. I put the function in multiple regions and had the clients randomly pick one as a way to load balance a little to fix it.

@saldous , aloha! Thanks for your attention.

console.log('Launch browser');
const browser = await pup.launch({ headless: false }); 

console.log('Opening page');
const page = await browser.newPage();

console.log('Go to page');
await page.goto('https://google.com');  

My script stoping on "Launch browser", and I can't see log with "Opening page".
And after some time I see the issue message.

UPD:

  1. I tried start puppeteer with dart (on wsl space) - not working
  2. I tried start puppeteer with dart in the virtual machine with lubuntu - working
  3. I tried start puppeteer with dart without WSL - working
  4. I tried start puppeteer with nodejs without WSL - working

.... so... something wrong with WSL, but I repeat - I used my script many taimes in last month :-(

@saldous
Copy link

saldous commented Sep 29, 2022

@paveltretyakovru did you allocate enough memory?

@paveltretyakovru
Copy link

@paveltretyakovru did you allocate enough memory?

@saldous Sorry, memory for what?

@phureewat29
Copy link

I got this error only when running on my Apple Silicon (with --platform linux/amd64 ) but it works perfectly on Intel CPU or cloud providers.

@AllanOricil
Copy link

AllanOricil commented Oct 7, 2022

puppeteer-cluster randomly crashes

image

// Create reference instance
const marked = require('marked')
const Handlebars = require("handlebars");
const fs = require('fs');
const nodeHtmlToImage = require('node-html-to-image');

const githubMarkdownTemplate = fs.readFileSync('./github-markdown-html-template.html', { encoding: 'utf-8' });
const githubMarkdown = marked.parse(`Environment: vdallano%0A%0A### Metadata Failures ###%0A| API Name |Type |Line |Column |Error Message |%0A | ------------- | ------------- | ------------- | ------------- | ------------- |%0A| Order_Record_Page |FlexiPage | | |We couldn't retrieve the design time component information for component c:rhcSignedDocumentUploader. |%0A%0A%0A### Vlocity Errors ###%0A| Errors |%0A | ------------- |%0A| error 1 |%0A| error 2 |%0A| error 3 |`.replaceAll('%0A', '\n'));
const template = Handlebars.compile(githubMarkdownTemplate);
const html = template({
	githubMarkdown
});

//fs.writeFileSync('./github-markdown.html', html, { encoding: 'utf-8' });

nodeHtmlToImage({
	output: './image.png',
	html
})
.then(() => console.log('The image was created successfully!'))
{
  "name": "markdown-2-image",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "handlebars": "^4.7.7",
    "html-to-image": "^1.10.8",
    "marked": "^4.1.1",
    "node-html-to-image": "^3.2.4"
  }
}

@ostappartyka
Copy link

ostappartyka commented Oct 12, 2022

lib puppeteer-extra helped me to resolve this issue

code example -> https://github.com/cobalt-intelligence/log-into-google-with-puppeteer/blob/master/src/index.ts

@koaladlt
Copy link

@bruriah1999 your entry function will have a response call. Once invoked the functions technically terminated which means all other tasks are considered background tasks and won’t execute.

Check the Function Execution Timeline in this article https://cloud.google.com/functions/docs/concepts/exec

Do you have a code example for this?

@RadianSmile
Copy link

I encounter the same issue on MacOS, after switch to {headless: false} then switch back to {headless: true}, it works. I think the computer need us to allow the chromium first with headless false, after that, it can work in headless mode silently.

@Kevjinx
Copy link

Kevjinx commented Feb 5, 2023

Had the same problem. There's a recent stackoverflow post about running puppeteer on WSL2 and the problem was that my firewall prevented access to my x-server.

I followed the instruction and got it to work!

https://stackoverflow.com/questions/73561240/running-puppeteer-on-wsl2

@aarhusgregersen
Copy link

I got this error only when running on my Apple Silicon (with --platform linux/amd64 ) but it works perfectly on Intel CPU or cloud providers.

This was the issue for me as well.

Setting up a rosetta terminal and running the command again works fine. Might be worth pointing out in the documentation.

@doteric
Copy link

doteric commented Apr 6, 2023

So what seemed to fix it for me is to simply make sure I'm spawning only one instance of the browser instead of many.
In case of both AWS Lambda/Google Cloud Functions the instance managing the function spins up, the first execution is totally fine, but the next execution (in a short timeframe) will fail, because the chrome instance is already up. A simple solution is to create separate function ala prepareBrowser and make sure to cache the returned browser and check inside the main handler whether it's there already or not. If it's there then just re-use it.
For example:

let browserPromise: Promise<puppeteer.Browser>;;
const prepareBrowser = async () => {
  // function responsible for launching chrome
}

const handler = () => {
  ...
  if (!browserPromise) {
    browserPromise = prepareBrowser();
  }
  const browser = await browserPromise;
  ...
}

I guess that killing the browser at the end of the function should also solve the problem, but "caching" seems to be more appropriate 🤔
Just make sure you await browser.close(), because if you don't do await then the browser won't close properly before the function ends.

@diogobd
Copy link

diogobd commented Apr 13, 2023

In GPC i had problem with timeout, when i instantiate the puppeteer out of the function.

This is my source code working

const puppeter = require('puppeteer');

//when instantiate out of the function report, a had a problem
/let browserPromise = puppeter.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--font-render-hinting=medium'
]
});
/

`
exports.report = async (req, res) => {
res.set("Access-Control-Allow-Origin", "http://localhost");
const url = req.query.url || '';
let content;

switch (req.get('content-type')) {
    case 'application/json':
        content = req.body;
        break;

    case 'application/octet-stream':
        content = req.body.toString();
        break;

    case 'text/plain':
        content = req.body;
        break;

    case 'application/x-www-form-urlencoded':
        content = req.body;
        break;
}

const type = req.query.type || 'image';//pdf
const browser = await puppeter.launch({
    headless: true,
    args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--font-render-hinting=medium'
    ]
});
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
await page.setDefaultNavigationTimeout(0);
if (url) {
    await page.goto(url);
} else {
    await page.setContent(content, {
        timeout: 0,
        waitUntil: 'domcontentloaded'
    });
}

setTimeout(async() => {
    if (type == 'image') {
        const image = await page.screenshot({
            fullPage: true
        });
        //await context.close();
        res.setHeader('Content-Type', 'image/png');
        res.send(image);    
    } else if (type == 'pdf') {
        let displayHeaderFooter = false;
        let footerTemplate = req.query.footerTemplate || '';
        if (footerTemplate) {
            displayHeaderFooter = true;
        }
        let landscape = req.query.orientation == 'landscape';
        const pdf = await page.pdf({
            landscape: landscape,
            displayHeaderFooter: displayHeaderFooter,
            footerTemplate: footerTemplate
        });
        res.setHeader('Content-Type', 'application/pdf');
        res.send(pdf);    
    }
    await browser.close();
}, 1000);

}
`

@Keshavdulal
Copy link

@bruriah1999 your entry function will have a response call. Once invoked the functions technically terminated which means all other tasks are considered background tasks and won’t execute.

Check the Function Execution Timeline in this article https://cloud.google.com/functions/docs/concepts/exec

Expanding upon this answer by @tbadlov
In my case I was using https cloud functions and all I had to do was call res.send("OK"); from the finally statement of innermost (or last) async function.

I have 1st async function to generate a file and 2nd async (inner) function to email the generated file.
Upon correctly signaling the end of 2nd func, my entire cloud function ran smoothly.

Example Code Snippet:


exports.sendOrderConfirmationEmail = functions.https.onRequest((req, res) => {
  return cors()(req, res, async () => {
    
    nodeHtmlToImage({
      output: "./outputs/Order-Confirmation.png",
      html: emailBody,
    })
      .then(() => {
        console.log("The image was created successfully!");

        const emailPayload = {}; // w/attachment

        sgMail
          .send(emailPayload)
          .then(() => console.log("Email sent"))
          .catch((error) =>
            console.error("Error @sendOrderConfirmationEmail", error)
          )
          .finally(() => {
            // Send an HTTP response To mark end of function execution - EXTREMELY IMPORTANT
            // https://cloud.google.com/functions/docs/concepts/execution-environment#execution-timeline
            res.send("OK");
          });
      })
      .catch((error) => console.error("Error generating PNG:", error));
  });
});

@carbonemys
Copy link

For anyone still struggling with this, I managed to fix it in Cloud Run by increasing the Request timeout setting and res.send it when everything is completely finished.

@flexeo
Copy link

flexeo commented Nov 9, 2023

I have exactly the same error with the latest version of puppeteer (21.5.0). Approximately one time out of 2, the error is impossible to catch with the try catch block, and the script ends by crashing.

/home/.../node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:59
void this.terminate(new Errors_js_1.TimeoutError(Waiting failed: ${options.timeout}ms exceeded));
^

TimeoutError: Waiting failed: 15000ms exceeded
at Timeout. (/home/.../node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:59:37)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)

try {	
  const pages = await currentBrowserInstance.browser.pages();
  const page = pages[0];
  await page.setViewport({ width: 100, height: 100 });
  const watchDog = page.waitForFunction('!!window.DRAW_FINISH', {timeout: timeout});
  await page.goto(backendURL, {timeout: timeout});
  await watchDog;
}
catch(e) {
  console.error(e);
}

@surxme
Copy link

surxme commented Jan 5, 2024

I removed the launch options:--single-process,it's work.🤡

@lutherjohnrichards
Copy link

@tbadlov Thank you, your suggestion worked for me.

I had this which was NOT working:

(async () => {
        const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
        const page = await browser.newPage();
        await page.setContent(htmlWithStyles);
        const pdfBuffer = await page.pdf({
            format: "A4",
            margin: { top: 0, bottom: 0, right: 0, left: 0 },
            printBackground: true,
        });
        await browser.close();
    })(outputFile);
 res.send(outputFile);
 return

Which returned immediately and stopped the puppeteer execution.

@nolimitdev
Copy link

nolimitdev commented Feb 15, 2024

In my case I run node run.js and one day mentioned error started. It was enough to add some useless console.log(111) to script and suddenly it started works again including removed console.log() later.

@yogastama
Copy link

I experienced this on my chromium, this happened because I gave chromium permission to push notifications to my mac, after I turned off the permission, it went back to normal.

Thank you for the disable google cloud functions suggestion above.

@jeremiascBTS
Copy link

I have a timeout problem with puppeteer 12.0.0, using a dockerfile with aws

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

Successfully merging a pull request may close this issue.