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?
evaluate evaluates your function in the page, not in your code's context. You can access everything that exist in the page's execution environment (e.g. window, document, etc.) but nothing that exists in your execution environment (e.g. startDate). That's because 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 - evaluate takes extra arguments which are all passed along to your function:
await startDateAttribute.evaluate(
(node, startDate) => node.setAttribute('value', startDate),
// ^^^^^^^^^ 2) extra argument(s) arrive here
//vvvvvvvvv 1) extra argument(s) getting passed in here
startDate
)
See docs: Evaluating JavaScript (explaining this exact pitfall) and ElementHandle#evaluate.
await startDateAttribute.evaluate(function(node) { node.setAttribute('value', startDate) });