Selenium WebDriver – How to click on a hidden link or Menu

07 May, 2014
How to click on a hidden link / hidden element / SubMenu which is only visible after hovering the mouse over to Menu.

WebDriver actually emulates user actions so it only does things what user is able to do. The webpage I was testing uses a JavaScript to load the menu and when I hover the mouse over on that Menu Text it loads he SubMenu. So at page load the SubMenu is hidden.


To emulate this action using WebDriver, I had to first move the mouse towards the main Menu (or click on it) to display the SubMenu. We can emulate this using Actions class provided WebDriver. Here is the code:

WebElement mainElement = driver.findElement(By.Id("mainEle")).Click();  
WebElement subElement = driver.findElement(By.Id("subEle")).Click();  
  
Actions builder = new Actions(driver);  
// Move cursor to the Main Menu Element  
builder.MoveToElement(mainElement).Perform();  
// wait 5 Secs for submenu to be displayed  
Thread.sleep(5000L);  
// Clicking on the Hidden SubMenu  
driver.findElement(By.Id("subElement")).Click();

The above code works like a charm with FF but it may not work with IE. In IE, mouse cursor does not stay on element and as a result popup becomes visible for a fraction of a second or doesn’t appear.

You can also use JQuery as another work around to this.

Using the .mouseover() method

js.ExecuteScript("return $(\"a:contains('Phones')\").mouseover();"); 
webDriver.FindElement(By.LinkText("Samsung")).Click();  

OR using the .hover() method

((JavascriptExecutor)driver).executeScript("$('div#Phones').hover();")  
webDriver.FindElement(By.LinkText("Sony")).Click();  


OR using the .mouseenter() method

((JavascriptExecutor)driver).executeScript("$('div#Phones').mouseenter();")  
webDriver.FindElement(By.LinkText("Sony")).Click();  

No comments:

Post a Comment