简体   繁体   中英

How to find “Cursor” position in webpage with Selenium Webdriver?

I just started learning Selenium Webdriver using java Script, the question what I have asked might me a silly one. But still wanted to know whether it is possible or not.

As per my question, please go through the below example

In any Login page, enter valid "Username" and click on "signin" button, it throws an error message "Please enter password" and the "cursor" will be located in "Password" field

So, we can get the error message via code. Now, how can we locate or identify the "Cursor" position in the webpage via code?

By definition, any widget that has focus also has the cursor. So driver.switchTo().activeElement() will return the currently focused WebElement. It doesn't actually change anything, just returns the active element. You can call

expectedElement.equals(driver.switchTo().activeElement());

to verify that expectedElement has focus.

Hey user3313128 with Selenium Web driver library it is only possible to figure out the current position by knowing the last place you moved it to.

Javascript sadly dose not give you an option to quickly get the X & Y.

An easy work around this is to simple run an simple function in the browser

async function (){
    await this.driver.executeScript(function(  ) { 
        let mouse = { x:0, y:0 }
        onmousemove = function(e){ mouse.x = e.clientX, mouse.y = e.clientY }
    })
}

this function will track your mouses X and Y in the browser the whole time

Then when you need to know mouse's location just call this script

mouse = driver.executeScript( function (){return mouse}) 

although the smart move is to track all of this within your JS on the server side at each mouse move and click().

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