DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Related

  • Extracting Data From Very Large XML Files With X-definition
  • Why React Router 7 Is a Game-Changer for React Developers
  • How to Get Plain Text From Common Documents in Java
  • Functional Programming Principles Powering Python’s itertools Module

Trending

  • AI-Driven Intent-Based Networking: The Future of Network Management Using AI
  • Web GenAI Microservices Creation: An Overview
  • Using Lombok Library With JDK 23
  • Faster Startup With Spring Boot 3.2 and CRaC, Part 1: Automatic Checkpoint

Greasemonkey Script To Get All Xpath Expressions Of 'a' And 'input Type=submit' Elements In A Document

By 
Snippets Manager user avatar
Snippets Manager
·
Apr. 02, 07 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
2.7K Views

Join the DZone community and get the full member experience.

Join For Free
This greasemonkey script uses the JS files loading mechanism that Carlo Zottmann's uses in his YUI GM script (http://ajaxian.com/archives/using-yui-in-greasemonkey-scripts)

The one JS file it loads (which you must host somewhere) must contain 3 functions: getElementXPath(), getElementIdx(), and gm_showXPath()

You will find getElementXPath and getElementIdx in a previous post of mine.

gm_showXPath() is provided here together with the GM script that loads the file and inserts a DIV on top of the HTML page with a link that when pressed will generate a pop-up and write all the XPATH expressions of 'a' and input submit elements in the document.


First the JS function that will call getElementXPath() for each doc element we are intersted on.


function gm_showXPath()
{
	var win = window.open("", window.location, "width="+700+",height="+300+",menubar=no,toolbar=no,directories=no,scrollbars=yes,status=no,left=0,top=0,resizable=yes");
	var xpathInfo = "";	
	var elt = null;
	var links = document.getElementsByTagName('a');
	var inputs = document.getElementsByTagName('input');
	// add click events
	xpathInfo +=  "

" + window.location + "

"; for (var i=0; i < links.length; i++) { elt = links[i]; var id = elt.getAttribute('id'); if (id != "gm_showxpath") { xpathInfo += "href=" + elt.getAttribute('href') + ",xpath="+getElementXPath(links[i]); xpathInfo += "
"; } } for (var j=0; j < inputs.length; j++) { elt = inputs[j]; var type = elt.getAttribute('type'); if (type != null && type.toLowerCase() == 'submit') { xpathInfo += "href=" + elt.getAttribute('href') + ",xpath="+getElementXPath(links[i]); xpathInfo += "
"; } } win.document.write(xpathInfo); win.document.close(); }
Here is the GM script that loads the JS file hosting the 3 functions I mentioned above. The SHOWXP.run function at the bottom of this GM script is the one that inserts the DIV at the top left corner of the page with a link to generate the XPATH "report" // ==UserScript== // @name Show xpaths. // @namespace http://snippets.dzone.com // @description Demo description goes here // @include http*://* // ==/UserScript== var hostname = "http://your_host_name:xyz"; // Settings used by the loader var GM_YUILOADER_CONFIG = { // List of JS libraries and CSS files to load. obj is used for the object // detection used in the loader. Basically, if the object already exists, // the script is not injected in the page. assets: [ { type: 'js', obj: 'XPATH', url: hostname + '/sandbox/xpath/xpath.js', onload: null} ], // What should be the max allowed loading time? In this example, the // script has 6 seconds to load the libraries and CSS files. timeout: 6000, // How often should the script check if everything was loaded? interval: 300, // What to trigger once all assets are loaded (a string). Example: execute // SHOWXP.run() (this will be eval()'ed later on, hence the string) runFunction: 'SHOWXP.run()', } // START LOADER CODE ////////////////////////////////////////////////////////// var DEMO; var GM_YUILOADER = { // Version of the loader VERSION: 20070103, // Simple internal timer to keep track of the passed time. loaderTimer: 0, }; // This function checks whether everything was loaded yet; if not, it'll wait // some more and call itself again. It'll do so until either all assets are // loaded or the max loading time (GM_YUILOADER.loaderTimer.timeout) is // reached. GM_YUILOADER.loaderCheck = function() { var ud = unsafeWindow.document; // Do we have a green light yet? if (ud.GM_YUILOADER_DOC.go) { DEMO = unsafeWindow.DEMO; delete ud.GM_YUILOADER_DOC; GM_YUILOADER.run(); } // Nope, not yet. Rinse & repeat! else { GM_YUILOADER.loaderTimer += GM_YUILOADER_CONFIG.interval; if (GM_YUILOADER.loaderTimer >= GM_YUILOADER_CONFIG.timeout) { return; } setTimeout(GM_YUILOADER.loaderCheck, GM_YUILOADER_CONFIG.interval); } } // Main function that initiates loading the external JS and/or CSS files GM_YUILOADER.loader = function() { if (document.contentType != 'text/html' || !document.body) { return; } var ud = unsafeWindow.document; // This object holds the important stuff to make this work. It's a property // of GM's unsafeWindow.document object. ud.GM_YUILOADER_DOC = { // Number of JS libraries loaded so far (increased by countLoaded() // below) numberLoaded: 0, // Total number of JS files. numberTotal: 0, // If this is bool true, we're good to go! This is checked by // GM_YUILOADER.loaderCheck(). go: false, // This function will be called by the onLoad events. countLoaded: function() { if (++this.numberLoaded == this.numberTotal) { this.go = true; } } }; // Now let's add the extra tags to the page that'll load the libraries and // CSS files. var head = document.getElementsByTagName('head').item(0); var numAssets = GM_YUILOADER_CONFIG.assets.length; for (var a = 0; a < numAssets; a++) { var tag; var asset = GM_YUILOADER_CONFIG.assets[a]; switch (asset.type) { // CSS file case 'css': tag = document.createElement('link'); tag.href = asset.url; tag.type = 'text/css'; tag.rel = 'stylesheet'; break; // Javascript library. case 'js': var injectScript = true; // Object detection try { injectScript = eval('window.' + asset.obj + ' === undefined'); } catch (e) {} if (injectScript) { tag = document.createElement('script'); tag.src = asset.url; // The crucial part: triggering document.GM_YUILOADER.countLoaded() // means keeping track whether all scripts are loaded yet. tag.setAttribute('onload', 'document.GM_YUILOADER_DOC.countLoaded();'); // How many JS libraries are we dealing with again? Let's keep // track. ud.GM_YUILOADER_DOC.numberTotal++; } break; } head.appendChild(tag); } // Did we actually include anything in the page? If so, trigger the // GM_YUILOADER.loaderCheck "watchdog". If not, just tell it to run the // main part of the script. if (ud.GM_YUILOADER_DOC.numberTotal > 0) { setTimeout(GM_YUILOADER.loaderCheck, GM_YUILOADER_CONFIG.interval); } else { ud.GM_YUILOADER_DOC.go = true; GM_YUILOADER.loaderCheck(); } } GM_YUILOADER.run = function() { // When we're here, we're good to go! eval(GM_YUILOADER_CONFIG.runFunction); } // The initial GM_YUILOADER trigger. setTimeout(GM_YUILOADER.loader, 500); // END LOADER CODE //////////////////////////////////////////////////////////// // START PAYLOAD SECTION ////////////////////////////////////////////////////// var SHOWXP = { }; // This function is triggered by the loader engine once the scripts are loaded SHOWXP.run = function() { var divElt = document.createElement('div'); divElt.setAttribute("id", "getxpath"); divElt.setAttribute("style", "background-color: black; font-weight: bold; font-size: 14px; top:0; left:0; position: absolute; border: 1px solid black;"); divElt.innerHTML = "Show XPaths"; document.body.appendChild(divElt); } // END PAYLOAD SECTION ////////////////////////////////////////////////////////
XPath Document Element

Opinions expressed by DZone contributors are their own.

Related

  • Extracting Data From Very Large XML Files With X-definition
  • Why React Router 7 Is a Game-Changer for React Developers
  • How to Get Plain Text From Common Documents in Java
  • Functional Programming Principles Powering Python’s itertools Module

Partner Resources


Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: