0

Can we catch in Selenium WebDriver events generated by the user (or events in general)? I know we can check state of page f.e. with WebDriverWait and ExpectedConditions, but that is not always appropriate.

Let's say I wanted to wait for user input to continue execution of test class. It would look something like this:

driver.get("https://www.google.com");

waitForKey(driver, org.openqa.selenium.Keys.RETURN);

/* rest of code */

driver.quit();

Where waitForKey would be implemented as:

public static void waitForKey(WebDriver driver, org.openqa.selenium.Keys key) {
     Wait wait = new WebDriverWait(driver, 2147483647);
     wait.until((WebDriver dr) -> /* what should be here? */);
}

Is there any way to do this?

xinaiz
  • 7,744
  • 6
  • 34
  • 78
  • [Have you checked out the answers here?](https://stackoverflow.com/questions/16746757/seleniumwebdriver-is-there-a-listener-to-capture-user-actions-in-the-browser-s?rq=1) – lloyd Jan 29 '18 at 00:50

1 Answers1

0

I never heard that Selenium support it. However, you can make it yourself by adding an eventListener to the document to create or change DOM. Then you can use Selenium to detect the change. See my example below.

The example uses JavaScript Executor to add a keydown listener to the document. When the key Enter has been pressed, it will create a div with ID onEnter and then add it to the DOM. Finally, Selenium will looking for the element with ID onEnter, and then it will click a link in the web.

driver.get("http://buaban.com");
Thread.sleep(5000);
String script = "document.addEventListener('keydown', function keyDownHandler(event) {" + 
                "    const keyName = event.key;" + 
                "    if(keyName===\"Enter\") {" +
                "        var newdiv = document.createElement('DIV');" +
                "        newdiv.id = 'onEnter';"+
                "        newdiv.style.display = 'none';"+
                "        document.body.appendChild(newdiv);" +
                "    }" +
                "});";

((JavascriptExecutor)driver).executeScript(script);

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("onEnter")));
driver.findElement(By.cssSelector("#menu-post a")).click();
Thread.sleep(5000);
Buaban
  • 5,029
  • 1
  • 17
  • 33