How to run a custom js function in playwright
Asked Answered
A

1

10

How can I run a custom js function in playwright? For example show an alert. I have already tried this way but it did not work.

var url = await page.evaluate(async() => {
  await function alert() {
    alert("alert");
  }

  await alert();
});
Afterdamp answered 2/8, 2020 at 20:33 Comment(3)
Looks like a stack overflow... won't the alert fn keep calling itself?Iona
@weltschmerz Not sure, I guess if you say so. This is just for example. New to this. Maybe that is why it is not working. Can you share a fix?Afterdamp
Well, first, I don't think you need any of the await and async keywords except for maybe the very first await (and you're using them wrong anyway, since you're using await on a function declaration). So basically try getting rid of all the async and await statements inside the call to page.evaluate, run it again, and let me know what you see.Iona
L
17

You would just do:

await page.evaluate(() => alert("alert"))

But keep in mind, that alert's are blocking in the JavaScript browser world and dismissed automatically by Playwright. See here how to interact with them (dismiss e.g.)

Lody answered 3/8, 2020 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.