Mouse hover and other mouse events in WebDriver

Mouse hover and other mouse events in WebDriver

This is widely known issue among web driver community, how to perform mouse hover.  I have many scenarios in my test where I needed to perform mouse hover to see calendar, email schedule etc. After many attempts, I found solution which is actually working very well for me but I am not sure if it’s going to work with your application of not.  Before going into coding we need to consider few limitations,

  • In Firefox, you have to maximize the webpage just before doing mouseover to get the focus on browser.
  • Works fine even in normal window size with other browser like IE and Chrome.



For mouse event, you  can call Action builder or even java script can do as well. I will not go in more theoretical detail but directly into coding. I am giving the same code I am using in my scripts, so please feel free to change or modify as per your need.

Using Action Builder:

[sourcecode language=”csharp”]
public static bool ElementMouseOver(IWebElement targetElement)
{
Size currentWinSize = _driver.Manage().Window.Size;
_driver.Manage().Window.Maximize();
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(_driver);
try
{
builder.MoveToElement(targetElement).Build().Perform();
Thread.Sleep(2000);//2 sec is just to for this blog.
//I use custome method to wait element being appeared after mouse hover event.
//You can use other variable wait time but make sure your give some pause
//otherwise mouse hover will happen for fraction of seconds and then disappear.

_driver.Manage().Window.Size = currentWinSize;
}
catch (Exception e)
{
loggerInfo.Instance.Message(e.Message);
return false;
}
return true;
}
[/sourcecode]


Using JavaScript

[sourcecode language=”csharp”]
public static void MouseHoverByJavaScript(IWebElement targetElement)
{

string javaScript = "var evObj = document.createEvent(‘MouseEvents’);" +
"evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
"arguments[0].dispatchEvent(evObj);";
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript(javaScript, targetElement);
}
[/sourcecode]

You can use above java script to perform other  mouse events like click/double click. Please refer initMouseEvent which you can use in above code.
                          
I implemented drag and Drop event as well using Action builder itself.
Drag And Drop

[sourcecode language=”csharp”]

IWebElement source = FindElement("blah blah");
IWebElement target = FindElement("blah blah");
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(_driver);
try
{
builder.DragAndDrop(source, target).Build().Perform();
}
catch (Exception e)
{
//log Exception.I use NLog.
}

[/sourcecode]

Everyone uses own approach to handle such events. I mostly use Firefox/Chrome for testing as IE some time very flaky. And personally I hate IE. I tested above code in FF/Chrome and it was working fine. I would like to learn new way to handle such events If you are aware of any and please don’t forget to post in comment below or email me via contact us page.

17 Comments

  1. I ran into a case where when I drag and drop I have to put a short sleep after moving the mouse and releasing the mouse button. To fix the issue I changed my DragAndDrop function to do this:

    Actions builder = new Actions(WTWebUiAuto.webDriver);
    builder.ClickAndHold(source);
    builder.MoveToElement(target, xOffset, yOffset);
    builder.Perform();

    Thread.Sleep(delayBeforeDropping);
    Actions builder2 = new Actions(WTWebUiAuto.webDriver);
    builder2.Release();
    builder2.Perform();

  2. Deepak

    GREAT lines of code.
    Solved my problem
    Thanks a lot

    public static void MouseHoverByJavaScript(IWebElement targetElement)
    {

    string javaScript = “var evObj = document.createEvent(‘MouseEvents’);” +
    “evObj.initMouseEvent(\”mouseover\”,true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);” +
    “arguments[0].dispatchEvent(evObj);”;
    IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
    js.ExecuteScript(javaScript, targetElement);
    }

  3. Sreekanth

    Hi,
    I am running the selenium scripts on Safari browser but its doesnt support interaction API. can you please send me the workaround javascript code for the below code please.

    Actions action = new Actions(driver);
    action.moveToElement(element);
    action.clickAndHold();
    action.moveByOffset(100,200).moveByOffset(-10, -20).moveByOffset(-10, -10).moveByOffset(-10, -20).build().perform();
    action.release().build().perform();

  4. The below mouse action code has worked for me while selecting a value from a drop-down :
    Actions act = new Actions(driver);
    act.moveToElement(driver.findElement(By.xpath(“”))).perform();
    act.moveByOffset(10, 0);(driver.findElement(By.xpath(“element path”))).click();

    1. Aditya

      Raveendra,
      Once you hover the mouse over the element, you just need to read that items in the same way you read other element. I think you are talking about some special case. Please share the issue with example.

  5. Sowjanya

    Hi Aditya,

    Drag and Drop is not working for me on chrome for react code.. my code is

    public void scrollGrid() throws Exception
    {
    Actions actions = new Actions(driver);
    actions.moveToElement(driver.findElement(By.xpath(“.//*[@class=’price-org’]”)));
    actions.click();
    actions.sendKeys(Keys.PAGE_DOWN);
    actions.build().perform();
    WebElement ele=null;
    WebElement ele2=null;
    int flag=0;

    do{
    try{
    //element to search for while scrolling in grid
    ele = driver.findElement(By.xpath(“.//*[@class=’price-org’] //span[contains(text(),’R4 AU/NZ’)]”));
    ele2= driver.findElement(By.xpath(“.//*[@class=’create-event-drop-target’]”));
    /*
    Actions operation = new Actions(driver);
    operation.dragAndDrop(ele, ele2).build().perform();*/
    Actions builder = new Actions(driver);
    builder.clickAndHold(ele);
    builder.moveToElement(ele2, 800,691);
    builder.perform();

    Thread.sleep(1000);
    Actions builder2 = new Actions(driver);
    builder2.release();
    builder2.perform();

    Thread.sleep(3000);
    flag=1;
    } catch(Throwable e){
    //scrolling the grid using the grid’s xpath
    // driver.findElement(By.xpath(“.//*[@class=’hierarchy’]”)).sendKeys(Keys.PAGE_DOWN);
    Thread.sleep(3000);
    }
    }while(flag==0) ;

    if(flag==1){
    System.out.println(“Element has been found.!!”);

    }else{
    System.out.println(“Element has not been found.!!”);
    }

    }

    It says element is found.. test case is pass.. but the element is not dropped into the target

  6. Prashant

    I am facing a issue here , I have a link which on hover creates dropdown of other link which on hover shows a single link and i need to click this link.
    Mother link (on hover)
    |
    Child Link (on hover)
    |
    grandchild (click)

    Can somebody help me in this , I am using Java
    Thanks.

Leave a Reply to Raveendra Cancel reply