Skip to content

Instantly share code, notes, and snippets.

@ebinnion
Last active May 28, 2021 12:47
Show Gist options
  • Save ebinnion/5969419 to your computer and use it in GitHub Desktop.
Save ebinnion/5969419 to your computer and use it in GitHub Desktop.
Will generate xpaths when elements clicked
/*!
* jQuery Cookie Plugin v1.3.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function raw(s) {
return s;
}
function decoded(s) {
return decodeURIComponent(s.replace(pluses, ' '));
}
function converted(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
return config.json ? JSON.parse(s) : s;
} catch(er) {}
}
var config = $.cookie = function (key, value, options) {
// write
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
config.raw ? key : encodeURIComponent(key),
'=',
config.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// read
var decode = config.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
var result = key ? undefined : {};
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = decode(parts.join('='));
if (key && key === name) {
result = converted(cookie);
break;
}
if (!key) {
result[name] = converted(cookie);
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return true;
}
return false;
};
}));
/*
* XPath - jQuery wrapper for the DOM 3 XPath API exposed by document.evaluate()
*
* Copyright © 2010 John Firebaugh
*
* Dual licensed under the MIT or GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
(function ($) {
var xp = function (xpath, contextNode) {
var iterator = document.evaluate(xpath, contextNode, null, XPathResult.ANY_TYPE, null),
node = iterator.iterateNext(),
nodes = [];
while (node) {
nodes.push(node);
node = iterator.iterateNext();
}
return nodes;
};
$.xpath = function (xpath) {
return $(xp(xpath, document));
}
$.fn.xpath = function (xpath) {
var nodes = [];
this.each(function () {
nodes.push.apply(nodes, xp(xpath, this));
});
return this.pushStack(nodes, "xpath", xpath);
}
})(jQuery);
// Use this function to return all attributes for an element
(function($) {
$.fn.getAttributes = function () {
var elem = this,
attr = {};
if(elem.length) $.each(elem.get(0).attributes, function(v,n) {
n = n.nodeName||n.name;
v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
if(v != undefined && v !== false) attr[n] = v
})
return attr
}
})(jQuery);
(function($) {
$.fn.generateXPath = function () {
var element = this,
path = '',
pathArray = [];
function buildPathArray() {
while( !empty(element[0].tagName) ){
var theId = element.attr('id');
if ( !empty(theId) ){
pathArray.push({ 'tag' : element[0].tagName, 'theIndex' : element.indexOfType(), 'theAttributes' : element.getAttributes() });
return;
}
else {
pathArray.push({ 'tag' : element[0].tagName, 'theIndex' : element.indexOfType(), 'theAttributes' : element.getAttributes() });
}
element = element.parent();
}
}
function buildXPath(){
for (var i = 0; i < pathArray.length; i++){
if ( !empty(pathArray[i].theAttributes.id) ){ // Case for this being an ID and terminating the loop
path = "//" + pathArray[i].tag.toLowerCase() + "[@id='"+pathArray[i].theAttributes.id+"']" + path;
}else {
path = "/" + pathArray[i].tag.toLowerCase() + "["+pathArray[i].theIndex+"]" + path;
}
}
}
buildPathArray();
buildXPath();
return path;
}
})(jQuery);
// Will return value for an element whether it is a form element (requiring .val())
// or a text element such as p and h3 (requiring .text())
(function($) {
$.fn.getValue = function () {
var element = this;
if ( !empty( element.text() ) ){
return element.text();
}else if ( !empty( element.val() ) ){
return element.val();
}
}
})(jQuery);
// Return 1-based-index of an element in relation to like tags
(function($) {
$.fn.indexOfType = function () {
var element = this,
prev = element.prevAll(element[0].tagName);
if ( empty(prev) ){
return 1; // For 1 indexing
}else {
return 1 + prev.length;
}
}
})(jQuery);
function empty (mixed_var) {
// version: 909.322
// discuss at: http://phpjs.org/functions/empty
var key;
if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || mixed_var === undefined || mixed_var === 'undefined') {
return true;
}
if (typeof mixed_var == 'object') {
for (key in mixed_var) {
return false;
}
return true;
}
return false;
}
function randomString(length) {
var result = '';
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (var i = length; i > 0; --i){
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
jQuery(document).ready(function($){
var org = 'ebinnion',
app = 'sandbox',
apiUrl = "https://api.usergrid.com/"+org+"/"+app+"/",
accessToken = null;
console.log(randomString(88));
$('a, input, textarea, button').click(function(e){
e.preventDefault();
var timestamp = Math.round(new Date().getTime() / 1000),
xPath = $(this).generateXPath();
console.log( xPath );
console.log( $(this).getValue() );
console.log( $.xpath(xPath).getValue() );
console.log('');
});
$('form').on('submit', function(){
var timestamp = Math.round(new Date().getTime() / 1000),
form_xpath = $(this).generateXPath(),
inputs = $(this).filter(':input'),
form_values = [];
for( var i = 0; i < inputs.length; i++){
form_values.push({});
}
// Selenium action should consist of locator, action, and value. Build this from form
console.log('');
});
});
@ebinnion
Copy link
Author

Need to write a different method for retrieving index. Possibly use prevAll(element[0].tagName)?

@ebinnion
Copy link
Author

On click, if element is a button, link, checkbox, or radio button use selenium click action.

If link has href, use clickAndWait.

@kirankdkd
Copy link

Can please help how to use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment