-2

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.

  • 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
  • Welcome to Stack Overflow! See: [How do I do X?](https://meta.stackoverflow.com/questions/253069/whats-the-appropriate-new-current-close-reason-for-how-do-i-do-x) The expectation on SO is that the user asking a question not only does research to answer their own question but also shares that research, code attempts, and results. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: [ask] – JeffC Aug 09 '17 at 13:24

1 Answers1

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];
}

reference: I'm storing click coordinates in my db and then reloading them later and showing them on the site where the click happened, how do I make sure it loads in the same place?

Murthi
  • 5,146
  • 1
  • 9
  • 15