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();
});
painotpi
  • 6,894
  • 1
  • 37
  • 70
Roboman Robo
  • 599
  • 2
  • 5
  • 16
  • 1
    Looks like a stack overflow... won't the `alert` fn keep calling itself? – Dennis Hackethal Aug 02 '20 at 20:38
  • @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? – Roboman Robo Aug 02 '20 at 20:44
  • 1
    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. – Dennis Hackethal Aug 02 '20 at 21:06

1 Answers1

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.)

Max Schmitt
  • 2,529
  • 1
  • 12
  • 26
pguardiario
  • 53,827
  • 19
  • 119
  • 159