I have the following (fairly) simple JavaScript snippet that I have wired into Greasemonkey. It goes through a page, looks for <a> tags whose href points to tinyurl.com
, and adds a "title" attribute that identifies the true destination of the link. Much of the important code comes from an older (unsupported) Greasemonkey script that quits working when the inner component that held the XPath implementation changed. My script:
(function() {
var providers = new Array();
providers['tinyurl.com'] = function(link, fragment) {
// This is mostly taken from the (broken due to XPath component
// issues) tinyurl_popup_preview script.
link.title = "Loading...";
GM_xmlhttpRequest({
method: 'GET',
url: 'http://preview.tinyurl.com/' + fragment,
onload: function(res) {
var re = res.responseText.match("<blockquote><b>(.+)</b></blockquote>");
if (re)
{
link.title = re[1].replace(/\<br \/\>/g, "").replace(/&/g, "&");
}
else
{
link.title = "Parsing failed...";
}
},
onerror: function() {
link.title = "Connection failed...";
}
});
};
var uriPattern = /(tinyurl\.com)\/([a-zA-Z0-9]+)/;
var aTags = document.getElementsByTagName("a");
for (i = 0; i < aTags.length; i++)
{
var data = aTags[i].href.match(uriPattern);
if (data != null && data.length > 1 && data[2] != "preview")
{
var source = data[1];
var fragment = data[2];
var link = aTags[i];
aTags[i].addEventListener("mouseover", function() {
if (link.title == "")
{
(providers[source])(link, fragment);
}
}, false);
}
}
})();
(The reason the "providers" associative array is set up the way it is, is so that I can expand this to cover other URL-shortening services as well.)
I have verified that all the various branches of code are being reached correctly, in cases where the link being examined does and does not match the pattern. What isn't happening, is any change to the "title" attribute of the anchor tags. I've watched this via Firebug, thrown alert()
calls in left and right, and it just never changes. In a previous iteration all expressions of the form:
link.title = "...";
had originally been:
link.setAttribute("title", "...");
That didn't work, either. I'm no newbie to JavaScript OR Greasemonkey, but this one has me stumped!