0

I have been working on this and have looked at other posts on StackOverflow but they did not answer my questions. This is a unique and specific question. How can I get then currentapple variable to successfully pass into the function? Right now I get undefined src errors. I'm doing web automation with puppeteer and node.js.

Code:

    var currentapple = 2;

    console.log(currentapple+" hi1");
    var appleurl= await page.evaluate(async (currentapple) => {
        console.log(currentapple+" hi2");

        var appleelement = await document.getElementsByClassName('ta');
        var appleurl = await appleelement[currentapple].src;
        
        //var gotourl = window.location.href = appleurl;
        //return appleurl;
        
        return await JSON.stringify(appleurl);
    });

Error:

UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'src' of undefined

Roboman Robo
  • 599
  • 2
  • 5
  • 16
  • Remove the parameter of the anonymous `.evaluate()` handler – Andreas Aug 07 '20 at 12:04
  • You are shadowing the variable by also using it as parameter; use `var imageurl = await page.evaluate(async () => {` –  Aug 07 '20 at 12:05

1 Answers1

1

You must supply the variable as additional parameter for page.evaluate:

var currentapple = 2;
var imageurl = await page.evaluate(async (currentapple) => {
    console.log(currentapple+" hi2");
}, currentapple);
Vaviloff
  • 16,282
  • 6
  • 48
  • 56