javascriptc#selenium-webdriverplaywright

What is the Playwright equivalent of Selenium's ExecuteScript function?


In Selenium (c#), you can use an IJavaScriptExecutor to execute javascript commands on IWebElements you find, using the arguments[index] string in your script. For example, if I want to use javascript to click on an element, I could use the following code to do so:

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", driver.FindElement(location));

In PlayWright, I know we have access to the Page.evaluate method, which lets us run custom javascript functions, but for the life of me, I can't figure out how to find the element I want to click on for the javascript method.

I have tried using a couple of things I found on the internet, but they haven't been working, even in situations where I know it works when I run it in selenium. Here's one example of what I've tried:

string clickScript = "var aTags = document.getElementsByTagName(\"option\");\r\n" +
"var searchText = \"Card\";rln" +
"var found; \r\n" +
"\r\n" +
"for (var i = 0; i < aTags. length; i+) {\r\n" +
"    if (aTags[i] textContent == searchText) {\r\n" +
"        found = aTags[i];\r\n" +
"        break; \r\n" +
"    }r\n" +
"}r\n" +
"\r\n" +
"found.click();"
    
await Page.evaluate(() => clickScript);

This compiles and runs, and I don't get any errors, but it just doesn't click on the element. My Javascript knowledge is very basic, and I've tried a few different scripts I've found, but none of them actually interact with the element.

However, when I use ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", driver.FindElement(location));, selenium is able to interact with the element without any problems.


Solution

  • Try this approach as well.

    var locator = page.Locator("some_selector");
    await locator.EvaluateAsync("element => element.click()");