- Jun 30, 2014
- 13,739
- 5,216
I would like to move the mouse from point A (random) to point B (an element) on the webpage using selenium and chrome driver.
As in simulating the mouse moving rather than just jumping from one point to another.
I have the coordinates of both the starting location and the destination element.
Unfortunately, there doesn't seem to be a way of moving the cursor to a specific point, it seems my options are MoveToElement and moveByOffset. Both of which work with offsets so you can only move a certain distance from the element you are trying to click on.
Moving the cursor
I'm using the code below to get the starting location/coordinates and the current coordinates
Getting the destination coordinates
I know the solution will be a loop that gradually reduces the offset until the X/Y target destination is reached or the destination element is in focus. It sounds simple but my attempts at slotting this all together have failed miserably so far.
Don't know why I'm struggling with this one, normally I find this shit easy as writing English.
Anyone done this before?
As in simulating the mouse moving rather than just jumping from one point to another.
I have the coordinates of both the starting location and the destination element.
Unfortunately, there doesn't seem to be a way of moving the cursor to a specific point, it seems my options are MoveToElement and moveByOffset. Both of which work with offsets so you can only move a certain distance from the element you are trying to click on.
Moving the cursor
Code:
Actions builder = new Actions(driver);
builder.MoveToElement(element, offsetX, offsetY).Perform();
I'm using the code below to get the starting location/coordinates and the current coordinates
Code:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("mousePosX = 0; mousePosY = 0; onmousemove = function(e){ mousePosX = e.clientX; mousePosY = e.clientY; console.log('Y:' + mousePosY + ' X:' + mousePosX); }; ");
IWebElement currentElement = driver.SwitchTo().ActiveElement();
builder.MoveToElement(currentElement, randomStartX, randomStartY).Perform();
int mousePosX = convertJSMousePos(driver.ExecuteScript("return mousePosX;"));
int mousePosY = convertJSMousePos(driver.ExecuteScript("return mousePosY;"));
Getting the destination coordinates
Code:
IWebElement link = driver.FindElement(By.LinkText("more info"));
System.Drawing.Point location = link.Location;
int targetXPostion = location.X;
int targetYPostion = location.Y;
I know the solution will be a loop that gradually reduces the offset until the X/Y target destination is reached or the destination element is in focus. It sounds simple but my attempts at slotting this all together have failed miserably so far.
Don't know why I'm struggling with this one, normally I find this shit easy as writing English.
Anyone done this before?