How to Pass Variable into an Evaluate Function

How can I pass variable into an evaluate function?

You have to pass the variable as an argument to the pageFunction like this:

const links = await page.evaluate((evalVar) => {

console.log(evalVar); // 2. should be defined now


}, evalVar); // 1. pass variable as an argument

You can pass in multiple variables by passing more arguments to page.evaluate():

await page.evaluate((a, b c) => { console.log(a, b, c) }, a, b, c)

The arguments must either be serializable as JSON or JSHandles of in-browser objects: https://pptr.dev/#?show=api-pageevaluatepagefunction-args

How can I pass variable into an evaluate function that evaluates an async function using Puppeteer?

Promise accepts in two arguments: resolve and reject. remove the current Post arg and it will work as expected.

let currentPost = 1;

await page.evaluate(async (currentPost) => {
await new Promise((resolve, reject) => {

var timer = setInterval(() => {

console.log(currentPost);
resolve();

}, 100);

});

}, currentPost);

Is there a way to pass a global variable into an $$eval function?

This is the signature:
page.$$eval(selector, pageFunction[, ...args])

So you can pass args as pageFunction args (3rd parameter onwards in $$eval and these will be passed as args to your function.

This is the updated code snippet.

const myVar = 100;
const menuData = await page.$$eval("div#Menu", (Menu1, varInsideFunction) => {
return Menu1.map((Menu1Element) => {
console.log(varInsideFunction); //testing to see if myVar is passed into browser context
...
})[0];
}, myVar).catch(console.error);

Pass arguments with page.evaluate

I've had that exact problem. It can be done with a little trickery, because page.evaluate also can accept a string.

There are several ways to do it, but I use a wrapper called evaluate, which accepts additional parameters to pass to the function that must be evaluated on the webkit side. You would use it like this:

page.open(url, function() {
var foo = 42;

evaluate(page, function(foo) {
// this code has now has access to foo
console.log(foo);
}, foo);
});

And here is the evaluate() function:

/*
* This function wraps WebPage.evaluate, and offers the possibility to pass
* parameters into the webpage function. The PhantomJS issue is here:
*
* http://code.google.com/p/phantomjs/issues/detail?id=132
*
* This is from comment #43.
*/
function evaluate(page, func) {
var args = [].slice.call(arguments, 2);
var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
return page.evaluate(fn);
}

Passing Variable to page.evaluate() function

Update: I need to pass putterID in like this:

const putterID = puttersObjectArray[putterPriorityIndexFound].id;
console.log(putterID) // 7729

await page.evaluate(async () => {
console.log(putterID)
await fetch(`https://www.examplestore.com/store/product/addtocartplp/?productId=${putterID}&X-Requested-With=XMLHttpRequest&_=1647970037149`, {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"99\", \"Google Chrome\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-newrelic-id": "VQABWFZUCBAEXFRRAQkCVVc=",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://www.examplestore.com/store/products/",
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
}, putterID);

Pass variables to a function inside Evaluate()

International Issue?

Depending on how you read the data, you can do one of the following:

Sub calcAnni()

Dim anni As Long
Dim data1 As String, data2 As String, dummy As String

data1 = Replace(Format([A1], "mm/dd/yyyy"), ".", "/")
data2 = Replace(Format([A2], "mm/dd/yyyy"), ".", "/")
dummy = "=DATEDIF(""" & data1 & """,""" & data2 & """,""Y"")"
anni = Application.Evaluate(dummy)
Debug.Print anni & " [" & data1 & "," & data2 & "]" & " - String"
'[A3] = data1
'[A4] = data2

End Sub

Sub calcAnni2()

Dim anni As Long
Dim date1 As Date, date2 As Date
Dim data1 As String, data2 As String, dummy As String
date1 = [A1]
date2 = [A2]
data1 = Replace(Format(date1, "mm/dd/yyyy"), ".", "/")
data2 = Replace(Format(date2, "mm/dd/yyyy"), ".", "/")
dummy = "=DATEDIF(""" & data1 & """,""" & data2 & """,""Y"")"
anni = Application.Evaluate(dummy)
Debug.Print anni & " [" & date1 & "," & date2 & "]" & " - Date"
Debug.Print anni & " [" & data1 & "," & data2 & "]" & " - String"
'[A3] = data1
'[A4] = data2

End Sub

Sub calcAnni3()

Dim anni As Long
Dim date1 As Date, date2 As Date
Dim dummy As String
date1 = [A1]
date2 = [A2]
dummy = "=DATEDIF(""" & Replace(Format(date1, "mm/dd/yyyy"), ".", "/") _
& """,""" & Replace(Format(date2, "mm/dd/yyyy"), ".", "/") & """,""Y"")"
anni = Application.Evaluate(dummy)
Debug.Print anni & " [" & date1 & "," & date2 & "]" & " - Date"
'[A3] = data1
'[A4] = data2

End Sub

Puppeteer - Passing a variable to page.evaluate()

Figured it out. Of course 5 minutes after posting to SO following hours of frustration, but here goes:

const x = 2;
let value = await page.evaluate((x) => {
return Promise.resolve(document.querySelector("#pageBody > div:nth-child(" + x + ") > table > tr > td").innerText)
}, x);
console.log(value);


Related Topics



Leave a reply



Submit