13

I'm using selenium WebDriver syntax. I know, that in selenium server-based syntax, you can fire an javascript event by doing:

Selenium selenium = new DefaultSelenium("localhost", server.getPort(),
            "*iexplore", "http://www.eviltester.com");
selenium.fireEvent("lteq30", "blur");

how do I do the same in an application, created with WebDriver (for example, FirefoxDriver)?

Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

2 Answers2

21

Unfortunately the Selenium WebDriver designers explicitly decided not to include this functionality in Selenium 2.

It's a deliberate decision to not include this feature in WebDriver, since it's usually a hack to work around synthesized events not behaving properly. We'd rather eliminate this need by providing great support for native events, so we'll continue improving that going forward. A user would never fire a focus event, they would click the form control. That's what your tests should be doing as well.

With that said, you can execute any javascript code you want. Thus you should look into how to fire events with javascript. Take at look at this StackOverflow question for inspiration.

Then you can do something like this:

FirefoxDriver driver = new FirefoxDriver();
driver.ExecuteScript("[your fire event javascript code]");

I'm sure you could create a wrapper function to basically accomplish the same thing as fireEvent.

Community
  • 1
  • 1
prestomanifesto
  • 12,528
  • 5
  • 34
  • 50
  • Will simply running the click() event in JS do the job or do I actually need to run the specific function in the code? If it's the latter, that seems like an ugly dependency to introduce into tests. – Tin Man Jan 29 '18 at 19:28
  • I understand their decision, but .sendKeys() should trigger keyDown keyUp change events, or perhaps .sendKeyWithEvents(). Otherwise you can't trigger basic events. – png Sep 07 '18 at 16:39
5

Another solution:

((JavascriptExecutor) driver).executeScript("return document.getElementById('element').blur()");
Hailei
  • 42,163
  • 6
  • 44
  • 69
user1514470
  • 51
  • 1
  • 1