1

I have this structure of code (including sockets and puppeteer):

client.on('find', (url) => {
    console.log(url);                         // url == "google.ru"
    (async function(){
        await page.goto(url);                 // url == "google.ru"
        await page.evaluate(async () => {
            var response = await fetch(url);  // url == undefined
            var json = await response.json();
            return json;
        });
    })();
});

I have tried some variations (closures etc.) but can't make it work. How to correctly pass url variable ?

el pax
  • 97
  • 2
  • 8

1 Answers1

2

.evaluate callback function runs in the page context, not in your main script context, that's why url is undefined.

Inside the callback you can access any variable defined in the browser global scope.

If you want to access url from inside .evaluate you can pass it as an argument.

page.evaluate(async (url) => {
    // browser context
    var response = await fetch(url);  
    var json = await response.json();
    return json;
}, url); // pass it as an argument
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98