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
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 pagewindow
object), so you can call it when you are insidepage.evaluate()
:Answer taken from this question, you can find a more in-depth discussion there.
You are almost there.
You need to stringify the function and then eval it back as a function inside the evaulate method: