lundi 21 décembre 2015

Integrating JS utility in any web application

I have created a javascript function which on click of any element in the page gives the Xpath of that element and all attributes of that element. This part is done.Now i want to use this function as a utility and should work on any web application. is there any way to do this? please sugeest me. below is the JS function:

  <script>
document.onclick= function(event) {
    if (event===undefined) event= window.event;                    
      var target= 'target' in event? event.target : event.srcElement; 
    var path= getPathTo(target);
    var attList = getAllAttributes(target);
    console.log(path);
};   
 function getPathTo(element) {
    if (element.id!=='')
        return "//*[@id='"+element.id+"']";

    if (element===document.body)
        return element.tagName.toLowerCase();

    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.toLowerCase() + '[' + (ix + 1) + ']';

        if (sibling.nodeType===1 && sibling.tagName === element.tagName) {
            ix++;
        }
    }
};     
function getAllAttributes(element){
    var arr=[];
    var attrs = element.attributes;
    for (var i = 0; i < attrs.length; i++) {
        arr.push({ AttributeName:attrs[i].name, Value:attrs[i].value});
}
    console.log(arr);
}
</script>




Aucun commentaire:

Enregistrer un commentaire