Puppeteer Fails to launch the browser - node.js

After creating a directory with an index.js file with the following code:
const puppeteer = require('puppeteer');
async function main() {
const browser = await puppeteer.launch({
headless: false,
args: ['--no-sandbox']
});
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({
path: 'example.png'
});
await browser.close();
}
// Start the script
main();
and then running npm init, and npm install puppeteer, the following error is returned:
node index.js
/mnt/c/Users/trgre/OneDrive/Desktop/puppeteer
test/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:214
reject(new Errors_js_1.TimeoutError(`Timed out after ${timeout} ms while trying to
connect to the browser! Only Chrome at revision r${preferredRevision} is guaranteed to
work.`));
^
TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at
revision r901912 is guaranteed to work.
at Timeout.onTimeout (/mnt/c/Users/trgre/OneDrive/Desktop/puppeteer
test/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:214:20)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
Node.js v17.1.0
Any ideas on what to do in order to run a puppeteer program, I am on windows using Ubuntu 20?

Related

Invalid chai property: browser when trying to run a test on puppeteer

i'm trying to run a test on a website using puppeteer and i want to use 'expect' assertion from chai but i keep getting this error and that my test failed.
const puppeteer = require('puppeteer')
const expect = require('chai').expect
describe('My First Puppeteer Test ', () => {
it( 'should launch the browser', async function() {
const browser = await puppeteer.launch({
headless: false,
slowMo: 10,
devtools: false,
defaultViewport: null,
args: ['--start-maximized']
})
const page = await browser.newPage()
await page.goto('http://example.com')
const title = await page.title()
const url = page.url()
const text = await page.$eval('h1', Element => Element.textContent)
const count = await page.$$eval('p', Element => Element.length)
expect(title).to.be.a('string', 'Example Domain')
expect(url).to.include('example.com')
expect(text).to.browser.a('string', 'example domain')
expect(count).to.equal(2)
await browser.close()
})
})
what's wrong with it?
do i need to add something in order for this to work?
this is the message i get from terminal
My First Puppeteer Test
1) should launch the browser
0 passing (1s)
1 failing
1) My First Puppeteer Test
should launch the browser:
Error: Invalid Chai property: browser
at Object.proxyGetter [as get] (node_modules\chai\lib\chai\utils\proxify.js:78:17)
at Context.<anonymous> (tests\example.test.js:25:24)
at runNextTicks (node:internal/process/task_queues:61:5)
at listOnTimeout (node:internal/timers:528:9)
at processTimers (node:internal/timers:502:7)

Unable to load script on puppeteer AWS Lambda

Im trying to add an external javascript file to puppeteer on Lambda.
const chromium = require('chrome-aws-lambda');
const browser = await chromium.puppeteer.launch({
....
});
const webPage = await browser.newPage();
await webPage.goto(url, { waitUntil: 'networkidle2', timeout: 0 });
await webPage.addScriptTag({
url: `https://code.jquery.com/jquery-3.6.0.min.js`,
});
But unable to load the script
ERROR Error: Loading script from https://code.jquery.com/jquery-3.6.0.min.js failed
at DOMWorld.addScriptTag (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.js:171:23)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async I (/var/task/src/functions/preparePages/handler.js:20:3689)
at async Runtime.E [as handler] (/var/task/src/functions/preparePages/handler.js:20:5400)

Puppeteer Protocol error (Page.navigate):

Error: Protocol error (Page.navigate): Cannot navigate to invalid URL
at Promise (/home/microservice/node_modules/puppeteer/lib/Connection.js:183:56)
at new Promise ()
at CDPSession.send (/home/microservice/node_modules/puppeteer/lib/Connection.js:182:12)
at navigate (/home/microservice/node_modules/puppeteer/lib/FrameManager.js:119:39)
at FrameManager.navigateFrame (/home/microservice/node_modules/puppeteer/lib/FrameManager.js:96:7)
at Frame.goto (/home/microservice/node_modules/puppeteer/lib/FrameManager.js:407:37)
at Frame. (/home/microservice/node_modules/puppeteer/lib/helper.js:111:23)
at Page.goto (/home/microservice/node_modules/puppeteer/lib/Page.js:629:49)
at Page. (/home/microservice/node_modules/puppeteer/lib/helper.js:111:23)
at module.exports (/home/microservice/node_modules/htmltopdf-puppeteer/index.js:19:16)\n at process._tickCallback (internal/process/next_tick.js:68:7)
Use http to access the url over network or use file:/// to access the local file
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] })
const page = await browser.newPage();
await page.goto("http://google.com");
or
await page.goto("file:///C:/ec2-user/report.html");

Firebase puppeteer PDF function times out due to Chrome revision

I have a Firebase function to create a PDF file. Lately, it times out due to a "Chrome revision"? Neither do I understand the error message, nor do I understand what is wrong. The function works, when I deploy it locally under MacOS.
TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r818858 is guaranteed to work.
at Timeout.onTimeout (/workspace/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:204:20)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
The function:
const puppeteer = require('puppeteer');
const createPDF = async (html, outputPath) => {
let pdf;
try {
const browser = await puppeteer.launch({
args: ['--no-sandbox']
});
const page = await browser.newPage();
await page.emulateMediaType('screen');
await page.setContent(html, {
waitUntil: 'networkidle0'
});
pdf = await page.pdf({
// path: outputPath,
format: 'A4',
printBackground: true,
margin: {
top: "50px",
bottom: "50px"
}
});
await browser.close();
} catch (e) {
console.error(e);
}
return pdf;
};
TimeoutError: Timed out after 30000 ms while trying to connect to the browser!
The aforementioned error is coming from the fact that as mentioned in the documentation:
When you install Puppeteer, it downloads a recent version of Chromium
Everytime you're executing Puppeteer you're running a Chromium in the backend to which Puppeteer will try to connect, hence when it can't connect to the browser this errors raises.
After doing multiple test I was able to execute the Cloud Function by adding the parameter headless on the launch option, since the documentation mentions that it should be true by default I don't quite understand why setting it manually allows the Cloud Function to finish correctly.
At the beginning I was trying with the timeout set to 0 to disable the error due to timeout, however it seems that it's not required, since by only adding headless it finished correctly, but if you find the same problem with the timeouts you can add it.
At the end my code looks like this:
const createPDF = async (html, outputPath) => {
let pdf;
try {
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
headless: true,
timeout: 0
});
const page = await browser.newPage();
await page.emulateMediaType('screen');
await page.setContent(html, {
waitUntil: 'networkidle0'
});
pdf = await page.pdf({
// path: outputPath,
format: 'A4',
printBackground: true,
margin: {
top: "50px",
bottom: "50px"
}
});
await browser.close();
console.log("Download finished"); //Added this to debug that it finishes correctly
} catch (e) {
console.error(e);
}
return pdf;
};

Run and install X server to make puppeteer works

on my linux server I running my nodejs project which should crawl single page app by puppeteer npm module.
Here is an example of the code I use:
const puppeteer = require('puppeteer');
(async () => {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://bvopen.abrickis.me/#/standings');
await page.waitForSelector('.category', { timeout: 1000 });
const body = await page.evaluate(() => {
return document.querySelector('body').innerHTML;
});
console.log(body);
await browser.close();
} catch (error) {
console.log(error);
}
})();
But I've got the next error:
0|www | Error: Failed to launch the browser process!
0|www | [5642:5642:0511/154701.856738:ERROR:browser_main_loop.cc(1485)] Unable to open X display.
0|www | [0511/154701.863486:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!
0|www | Most likely you need to configure your SUID sandbox correctly
0|www | TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md
I searched a lot how to install X server and tried a lot of things like sudo apt-get install xorg openbox but it doesn't helps.
Looks like puppeteer wants to start the browser in a non-headless mode but as you don't have xorg installed it failed. But I would say that's not what you want when it's running on a server anyways. So there is no need to install xorg or anything.
Maybe try to launch the puppeteer browser with following options:
await puppeteer.launch({
headless: true,
args: [
"--disable-gpu",
"--disable-dev-shm-usage",
"--no-sandbox",
"--disable-setuid-sandbox"
]
});

Resources