I need to create an Object spy, i.e. get element locator that is under the mouse, while mouse is controlled by user. I see a lot of methots at Selenium API but could not find appropriate ones. I know that there's a lot of tools already exist to do this, but anyway need to implement my own. Any ideas how to implement this using Selenium? Thanks.
Asked
Active
Viewed 967 times
-2
-
You can use firebug with firepath addon to get the locator xpath/css value on firefox. – Murthi Aug 09 '17 at 12:11
-
You should rather use proxy – Fenio Aug 09 '17 at 12:14
1 Answers
0
You can use the following javascript to get the element xpath under the mouse. Just paste the below code in your browser console. Then right click on any element it will give the xpath for the element under the mouse click.
document.onclick= function(event) {
if (event===undefined) event= window.event; // IE hack
var target= 'target' in event? event.target : event.srcElement; // another IE hack
var root= document.compatMode==='CSS1Compat'? document.documentElement : document.body;
var mxy= [event.clientX+root.scrollLeft, event.clientY+root.scrollTop];
var path= getPathTo(target);
var txy= getPageXY(target);
alert('Clicked element '+path+' offset '+(mxy[0]-txy[0])+', '+(mxy[1]-txy[1]));
}
function getPathTo(element) {
if (element.id!=='')
return 'id("'+element.id+'")';
if (element===document.body)
return element.tagName;
var ix= 0;
var siblings= element.parentNode.childNodes;
for (var i= 0; i<siblings.length; i++) {
var sibling= siblings[i];
if (sibling===element)
return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
if (sibling.nodeType===1 && sibling.tagName===element.tagName)
ix++;
}
}
function getPageXY(element) {
var x= 0, y= 0;
while (element) {
x+= element.offsetLeft;
y+= element.offsetTop;
element= element.offsetParent;
}
return [x, y];
}

Murthi
- 5,299
- 1
- 10
- 15