Code:
// All coding praise to biznatchio. I came up with this idea months ago, but could never
// get the damn thing to work. He looked at it twice and pumps out a flawless version
// of what I wanted in the first place. I'm leaving his comments in here so if people
// want to learn more about it, go right ahead, because I scoured the internet for
// a good way to do this and found jack and shit, respectively.
function checkURL(e) {
// Since this function is called as an event handler, a DOM event object is passed
// in as a parameter, which we take in as "e". The event object contains an originalTarget
// property, which tells us which object initiated the load event -- this will be the
// HTMLDocument object that just finished loading. By doing it this way and not using
// window._content, the load events will be handled correctly if a page loads in a
// background tab, since e.originalTarget will always point to the right document, whereas
// window._content always points to the foreground tab.
var doc = e.originalTarget;
var loc = doc.location;
try {
if ( loc && loc.href ) {
if ( loc.href.match( /^http:\/\/(images\.)?google\.(.*?)\//i ) ) {
changeLinks(doc);
}
}
}
catch (ex) { }
}
function selectNodes(doc, context, xpath) {
var nodes = doc.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var result = new Array( nodes.snapshotLength );
for (var x=0; x<result.length; x++) {
result[x] = nodes.snapshotItem(x);
}
return result;
}
function changeLinks(doc) {
// Get a list of all A tags that have an href attribute containing the start and stop key strings.
var googLinks = selectNodes(doc, doc.body, "//A[contains(@href,'/imgres?imgurl=')][contains(@href,'&imgrefurl=')]");
for (var x=0; x<googLinks.length; x++) {
// Capture the stuff between the start and stop key strings.
var gmatch = googLinks[x].href.match( /\/imgres\?imgurl\=(.*?)\&imgrefurl\=/ );
// If it matched successfully...
if (gmatch) {
// Replace the link's href with the contents of the text captured in the regular expression's parenthesis.
// The decodeURI fixed the special characters issue. (thanks Tivac)
googLinks[x].href = decodeURI(gmatch[1]);
}
}
}
window.addEventListener('load', checkURL, true); |