I have some URL parameters that I need to pass to Puppeteer via query strings. Everything works fine unless I define the necessary variable before I call the .evaluate() function. For instance, if I get the parameters of a URL, create a variable for a specific parameter, run .evaluate(), and try to access the variable within that it comes back undefined.
Here is an example
const testurl = 'https://example.com/app.js?&url=https://example.com/pagetocrawl.html&elements=.links'
const params = new URLSearchParams(testurl);
const url = params.get('url');
const elements = params.get('elements');
const networkidle = 'networkidle2';
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url, {waitUntil: networkidle});
pageitems = await page.evaluate(() => {
let results;
let items = document.querySelectorAll(elements);
items.forEach((item) => {
results += item.innerHTML;
});
return results;
});
The above code always returns an error saying that the elements variable is undefined. If I try to declare it inside the evaluate() call then it says that params is undefined, so unless I know what element to look for without having to get that from the URL I can't crawl the page. I tried changing evaluate(()=> to evaluate((params) => and then declaring the elements variable but that caused an error saying "Cannot read property 'get' of undefined." How do I define the variables outside the evaluate() function and be able to access them inside of it? Right now the next thing I can think of would be to make another call to get the current URL inside the evaluate() function, create a new params variable based on that, and create a new elements variable that gets its value from the new params variable.