2

I have a test.html page, here's code for it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
    </head>
    <body>
        <span id="test" onMouseover="alert('1')">this is new one</span>
    </body>
</html>

I want to use Selenium JavascriptExecutor to simulate mouse over event on span in test page, so I wrote code like this:

@Test
public void testJSExecutor(){
    System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
    webDriver = new FirefoxDriver();
    webDriver.get("file:\\\\C:/test.html");

    String script = "function test(){var t=document.getElementById('test');"
            + "if( document.createEvent ) {"
            + "var evObj = document.createEvent('MouseEvents');"
            + "evObj.initEvent( 'mouseover', true, false );"
            + "elem.dispatchEvent(evObj);"
            +"} else if( document.createEventObject ) {"
            + "elem.fireEvent('onmouseover');"
            +"}} window.onload=test;";
    jsExecutor = (JavascriptExecutor) webDriver;
    jsExecutor.executeScript(script);
}

But after run this code, no alert prompted.

How could mouse over event be valid so alert could be prompted?

1
  • Have you tried using Actions class to do mouseover? Commented Jan 17, 2014 at 5:29

1 Answer 1

3

You can simulate the mouse hover action using the below code..

Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.id("test"));
actions.moveToElement(menuHoverLink);
actions.perform();
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thanks a lot. :) And sorry for can not vote your answer up, because of less reputation. :(
Accepted this answer, thanks again for your help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.