Search code examples
javascriptpuppeteerwebautomation

How to pass the currentapple variable into this function?


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


Solution

  • 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);