I am using playwright at the moment, and want to write a function which contains an inner arrow function, something along the lines of
async function setSearchDate(startDate='2021-12-07') {
....do something...
const startDateAttribute = await page.$(searchStartDate);
await startDateAttribute.evaluate(node => node.setAttribute('value', startDate));
but somehow the inner arrow function does not see startDate value.
the error I’m getting is "elementHandle.evaluate: ReferenceError: startDate is not defined".
The code works well if I hardcode startDate value in the arrow function.
How can I pass that value?
>Solution :
evaluate evaluates your function in the page, not in your code’s context. In the page’s context, there is no variable startDate (unless the page defined its own window.startDate…).
To pass parameters, you must make use of the ...args:
await startDateAttribute.evaluate((node, startDate) => node.setAttribute('value', startDate), startDate)
See docs: Evaluating JavaScript (explaining this exact pitfall) and ElementHandle#evaluate.