In Selenium (c#), you can use an IJavaScriptExecutor
to execute javascript commands on IWebElement
s 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");rn" +
"var searchText = "Card";rln" +
"var found; rn" +
"rn" +
"for (var i = 0; i < aTags. length; i+) {rn" +
" if (aTags[i] textContent == searchText) {rn" +
" found = aTags[i];rn" +
" break; rn" +
" }rn" +
"}rn" +
"rn" +
"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.
2
Answers
The other answer listed pointed out what the problem was with my specific code. For anybody else who may come here looking for answers, here's what I'm doing:
This finds the element by the id, and then calls the
element.click()
method. This has worked in every situation that it does for selenium.You have to pass a string to
EvaluateAsync
: