skip to Main Content

Basically, I have a function:

const parseToNumber = (inputString) => {
   const cleanedString = inputString.replace(/[^0-9a-zA-Z]+/g, '');
   const numberValue = parseInt(cleanedString);
   return numberValue;
}

I’m trying to pass it to the evaluate method:

const parseToNumber = (inputString) => {
   const cleanedString = inputString.replace(/[^0-9a-zA-Z]+/g, '');
   const numberValue = parseInt(cleanedString);
   return numberValue;
}

I’m getting the error:

parseToNumber is not a function

what am I doing wrong?

async function getData(){
  let browser = await puppeteer.launch({
    headless: false,
    slowMo: 100,
    defaultViewport: {
        width: 1280,
        height: 1024,
    },
    let page = await browser.newPage();
    const url= "MY_URL";
    await  page.goto(url, {
        waitUntil: "networkidle0",
    });

    await page.evaluate(async (parseToNumber)=>{
       parseToNumber("2,42$");
    },parseToNumber);

 })
 .catch((err) => console.log("error loading url", err));

}
getData()

2

Answers


  1. You cannot pass a function directly into page.evaluate(), but you can call another special method (page.exposeFunction), which expose your function as a global function (also available in as an attribute of your page window object), so you can call it when you are inside page.evaluate():

    var myFunc = function() { console.log("test"); };
    await page.exposeFunction("myFunc", myFunc);
    
    await page.evaluate(async () => {
       await myFunc();
       return true;
    });
    

    Answer taken from this question, you can find a more in-depth discussion there.

    Login or Signup to reply.
  2. You are almost there.

    You need to stringify the function and then eval it back as a function inside the evaulate method:

    await page.evaluate(async (parseToNumber) => {
        eval(parseToNumber)
        parseToNumber("2,42$");
    }, parseToNumber.toString())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search