简体   繁体   中英

Catching user-generated events in selenium webdriver

Can we catch in Selenium WebDriver events generated by the user (or events in general)? I know we can check state of page fe 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM