Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Greasemonkey script to get all xpath expressions of 'a' and 'input type=submit' elements in a document

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 +=  "<h2>" + window.location + "</h2>";
	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 += "<br>";
		}
	}
	
	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 += "<br>";
		}
	}
	
	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 = "<a style='color: FF0000' id='gm_showxpath' href='javascript:gm_showXPath()'>Show XPaths</a>";
	document.body.appendChild(divElt);
}

// END PAYLOAD SECTION ////////////////////////////////////////////////////////


BlockFlash-Revisited.user.js

// ==UserScript==
// @name		BlockFlash-Revisited
// @namespace		http://snippets.dzone.com/posts/show/3054
// @description	Do not start Flash animation until you click on them.
// @include		*
// @exclude		http://www.macromedia.com/*
// @exclude		http://www.atomfilms.com/*
// @exclude		http://uploads.ungrounded.net/*
// @exclude		http://www.albinoblacksheep.com/*
// ==/UserScript==

/*
	Revised by Andrew Pennebaker (andrew.pennebaker@gmail.com)

	Author: Jos van den Oever (jos@vandenoever.info)

	License: GPL

	Version history:
		2006-02-12: initial version
		2006-11-28: changed appearance

Inspiration for this script comes from the removeFlash script and the FlashBlock firefox extension.
*/

(function () {
	var objects=document.getElementsByTagName("object");

	for (i=0; i<objects.length; i++) {
		var flash=objects[i];

		if (flash.innerHTML.match(/.swf|shockwave|flash/)) {
			var placeholder=document.createElement("div");

			placeholder.style.cursor='pointer';
			placeholder.style.background='orange'; // 'gray '
			placeholder.style.textAlign='center';
			placeholder.style.color='black';
			placeholder.innerHTML="[Play Flash]";

			flash.parentNode.insertBefore(placeholder, flash);
			flash.on=false;

			placeholder.addEventListener(
				'click',
				function() {
					if (flash.on) {
						flash.style.display='none';
						placeholder.innerHTML="[Play Flash]";
						flash.on=false;
					}
					else {
						flash.style.display='';
						placeholder.innerHTML="[Stop Flash]";
						flash.on=true;
					}
				},
				true
			);

			flash.style.display='none';
		}
	}
})();

2ch RSS Icon

// ==UserScript==
// @name  2ch RSS Icon
// @namespace  http://d.hatena.ne.jp/youpy/
// @include  http://*.2ch.net/test/read.cgi/*
// @exclude  http://b.hatena.ne.jp/*
// ==/UserScript==

(function () {
 var a = document.createElement('a');
 a.href = location.href.replace(/^http:\/\/(\w+\.2ch\.net\/)test\/read\.cgi\/(.+)$/, "http://rss.s2ch.net/test/-/$1$2");
 var image = document.createElement('img'); 
 image.src = 'data:image/png;base64,'+
    'iVBORw0KGgoAAAANSUhEUgAAACQAAAAOCAMAAABw6U76AAAAA3NCSVQICAjb4U/gAAADAFBMVEX/'+
    '///18e346N3/5tXv5Nz33czw2svo18z20rvw0Lv/yKTmzLrwxqrgyrreybrowqrwvJnfv6nvsYj0'+
    'qXflrYjxqHfTsJnlo3fVp4f/mlfgoXfunGbeoHbWnXbjmGbFoIfflma7nIfJmHffjFXsh0TmhUS6'+
    'kXe5kXf0gDPUiFXufjPfgkTNhVX2dyLHglXxdSLSfUTkdy6zhWXedzO+f1WqgWa3fFT/ZgDScjPd'+
    'bSLraBH3YwCseFXFbTPvYACkdFTsXgDmXADiXQW4aDPGYyLUXxGzZjPeWQDNXBGhaUTZVwDGWRGm'+
    'YTPTVADPUwDHUACyURGUWjPFSgC7SwCcUyK1SACsRQCbSBGoQwCNQxGcPgCZPQCTOwB9MwI/GgEh'+
    'DgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABJnr9zAAABHUlEQVR4nIWRWVODMBSFL5XWJVbc60K1'+
    '7gvuVYNGUuIWRQMtSNG6/f9/YQLTaRkfel7Omcw3uWfuhaGxgTqFRaxElHAWKaVp7Dr+zqDdum3b'+
    'T4IRTLZM8+BeUHK9YladgJEeBKnKbX5cSNOdmE4dRW4/dPG4p8FZWICdTmAZzgboH/FDzQhyUCti'+
    'o7AdAawlgcfZHOjPseDcJfmfTIBEjMgZ+nxT7KthE+fRv05aK3bJpKZSIjZL6mk1zndaB2hIiPGr'+
    'mibncs4tA+CL5zuNg/YWFJ3Q80pwUzVDn1ugf+agV58WQW/LRkiH4feKXEgZ4DK87UEzSy8MH1bM'+
    'k/osQlNHEafLBkILTZ/2QTi7AFVijFGVpbvds3R+Bur3DxzBWgFMxGSIAAAAAElFTkSuQmCC';
 image.width = 36;
 image.height = 14;
 a.appendChild(image);
 document.body.appendChild(a);
})();

Google Redirector

// ==UserScript==
// @name          Google Redirector
// @namespace     http://d.hatena.ne.jp/youpy/
// @include       *
// ==/UserScript==

(function() {
    var targets = document.evaluate('//a[starts-with(@href, "http")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0; i < targets.snapshotLength; i ++) {
	targets.snapshotItem(i).href = 'http://www.google.com/url?sa=D&q=' + encodeURIComponent(targets.snapshotItem(i).href);
    }
})();

Campfire Bot

// ==UserScript==
// @name Campfire Bot
// @namespace http://d.hatena.ne.jp/youpy/
// @description bot on campfire
// @include http://*.campfirenow.com/room/*
// ==/UserScript==

(function (){
    getLastMessage = function() {
	div = document.evaluate("//tr[contains(@class,'text_message') and not(contains(@class,'you'))]/td[@class='body']/div", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	return div.snapshotItem(div.snapshotLength - 1).innerHTML;
	
    }
    
    window.setInterval(
		       function() {
			   last_message = getLastMessage();
			   if(this.last_message != (sorted = last_message.split('').sort().join(''))) {
			       this.last_message = sorted;
			       if(last_message.match(/^\//)) {
				   switch(last_message) {
				   case '/now':
				       this.chat.speaker.speak(new Date().toString());
				       break;
				   }
			       } else  {
				   this.chat.speaker.speak(last_message.split('').reverse().join(''));
			       }

			   }
		       }, 3000);
})();


residents at here

Klaus Nomi

// ==UserScript==
// @name nomi
// @namespace http://www.bigbold.com/snippets/user/youpy
// @description NOMI
// @include *
// ==/UserScript==

(function (){
imgs = document.getElementsByTagName('img');
for(i = 0; i < imgs.length; i ++) {
imgs[i].src = 'http://images.google.com/images?q=tbn:v0zJeXKeczEJ:www.icicom.up.pt/blog/tendadosindios/archives/klausnomi1.jpg'
}

})();

Block Sponsored Links in Amazon.co.uk search results


// ==UserScript==
// @name          amazon-sponsored-links
// @namespace     chillihead
// @description   Remove sponsored links from Amazons search results
// @include       http://www.amazon.co.uk*
// ==/UserScript==


if(document.getElementsByTagName("span")!=null)
{
  var s = document.getElementsByTagName("span");
  
  for(var i = 0; i < s.length; i++)
  {
    if(s[i].getAttribute("class") != null)
    {
      var cls = s[i].getAttribute("class");
      if(cls == "h1")
      {
        if(s[i].innerHTML != null)
        {
          var txt = s[i].innerHTML;
          if(txt == "Sponsored Links:")
          {
            // great-grandparent of this span is the containing table.
            var theTable = s[i].parentNode.parentNode.parentNode;
            // get the tables parent
            var tableParent = theTable.parentNode;
            // remove the table of sponsored links.
            tableParent.removeChild(theTable);
          }
        }
      }
    }
  }
}

To prevent Greasemonkey user scripts from executing on your web site

I found this code on Mark Pilgrim's website, it's his code.

To prevent Greasemonkey user scripts from executing on your web site, put this line within the HEAD of every page:

&lt;script type="text/javascript"&gt;
    window.addEventListener = null;
&lt;/script&gt;

greasemonkey -- allmusic.com crap-blocker

// ==UserScript==
// @name          get rid of amg crap
// @namespace     polestar
// @include       *allmusic.com*

// ==/UserScript==

(function()
{
    inner = 'AMG blocker';
    amgCrap = document.getElementById( 'adverttop' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'header' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'NR' );
    amgCrap.innerHTML = inner;
    amgCrap = document.getElementById( 'right-sidebar' );
    amgCrap.innerHTML = inner;
})();
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS