Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute the OnClick javascript function via selenium webdriver without the click

I am building a new test case and have ran into a new issue I am not sure how to get around. I need to click on an element that is both visiblity: hidden and display: none or at least need a way to execute the javascript function it calls. In the passed I have been able to use IJavascriptExecutor to change an elements visibility or display but this option is no good for this test case as I am dealing with an array of elements that I locate at runtime using `Driver.FindElements' so I cannot get the exact selector to use my old method for changing display.

IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
var script = String.Format("document.querySelector('{0}').style.display='inline-block';", selector);
js.ExecuteScript(script);

Attached is a screenshot of the html and the css attributes for the element in question.

The way I see it I have two options I can make this test not dynamic and exercise the functionality on a single hardcoded element (yuck!), or I can figure out how to do this dynamically. So my hope (probably a fools hope) is that I can somehow call the onClick event bound to this button without actually clicking on it. enter image description here

like image 931
Buster Avatar asked Jun 26 '17 21:06

Buster


2 Answers

You could extract the onclick attribute and send it as parameter. You also don't need to use IJavaScriptExecutor, IWebDriver extends this interface so you can just call ExecuteJavaScript method

IWebElement buttonToClick;
string script = buttonToClick.GetAttribute("onclick");
driver.ExecuteJavaScript<object>(script);

You can also try clicking it with JavaScript

driver.ExecuteJavaScript<object>("arguments[0].click();", buttonToClick);
like image 150
Guy Avatar answered Nov 14 '22 22:11

Guy


It is possible to execute a JavaScript click on a IWebElement via an IJavaScriptExecutor, regardless of visibility.

Sounds like your issue stems from not being able to identify which element to click at runtime, I would take a look at XPaths.


In the meantime, here's an example of how to JavaScript click all <button> elements with an onclick event attribute, using an XPath:

IReadOnlyCollection<IWebElement> buttons =
    Driver.FindElements(By.XPath(".//button[@onclick]"));
IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
foreach (IWebElement button in buttons)
{
    js.ExecuteScript("arguments[0].click();", button);
}
like image 43
budi Avatar answered Nov 14 '22 23:11

budi