Sarah
Sarah

Reputation: 1

Selenium JavaScriptExecutor click function works only first time

On the UI I have a checkAll button which is implemented as a span under a div block. clicking it become hard so I used JavaScriptExcutor. I want click it two times. the code is as following 6 lines. the line3 always succeeded, but line 6 always fail silently (no error or exception, but click not happening). if I comment out line 3 then line 6 will function. why? please help me.

IJavaScriptExecutor executor = (IJavaScriptExecutor)drv;
IWebElement chkAll = TaskerStatus.FindElement(By.Id("header3-column0"));
executor.ExecuteScript("arguments[0].click();", chkAll);

cmdBar1collapseAll.Click();
expandAllBtn.Click();
executor.ExecuteScript("arguments[0].click();", chkAll);

Upvotes: 0

Views: 643

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193208

If I have understood the usecase / issue properly, Line 6 i.e.:

executor.ExecuteScript("arguments[0].click();", chkAll);

fails silently, i.e. no error or exception and the click() not happening as well.

But again if you comment out line 3 i.e. the first instance of:

executor.ExecuteScript("arguments[0].click();", chkAll);

Then line 6 i.e. the second instance of:

executor.ExecuteScript("arguments[0].click();", chkAll);

functions well.

The reason Line 6 is failing because when you invoked click() on the IWebElement chkAll a JavaScript / jQuery might have been active.

Solution

You need to induce WebDriverWait for the IWebElement chkAll to be clickable before you invoke the click at Line 6 and you can update Line 6 as follows:

executor.ExecuteScript("arguments[0].click();", new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(TaskerStatus.FindElement(By.Id("header3-column0")))));

Upvotes: 2

Related Questions