Friday, May 29, 2009

Userscript to change links

Why I set out to create this very short script doesn't really matter. Sometimes it is just handy to change a link on a website, but you don't have control over the source code. In a broader perspective, this method actually changes a specified attribute for each specified HTML element, and in that perspective is actually more generally useful.

Well okay, this is the situation. Our CMS gives us the option to change the configuration options for systems we sell. However, for certain systems our Sales department asked us to only use options we have in stock, so delivery times can stay as short as possible. Of course this information is not displayed in the page itself. It is however returned from the database. We are not allowed to make changes to the source of our CMS, but what my colleague did, is copy the specific JSP file, and change the output as to show whether a product is a stockproduct or not. This new file we have to access manually for each component change. This is bothersome in my eyes, and that's why I set out to create a small userscript for IE7Pro.

On a side note, we use a lot of different userscripts for both Internet Explorer (through IE7Pro) and FireFox (through GreaseMonkey) to enhance efficiency or fix annoying inefficiencies (small but relevant difference).

So I basically needed to change every link on pageA.jsp that linked to pageB.jsp?value=someID to pageB2.jsp?value=someID.




// ==UserScript==
// @name Show external status
// @namespace qrazi.blogspot.com
// @description Replace an attribute of specified element
// @include http://pages.where.this.should.apply*
// @exclude http://pages.where.this.absolutely.shouldnt.apply(optional)
// @version 1.0
// ==/UserScript==

var elm = document.getElementsByTagName("a");//or any other kind of element
for(i = 0; i<elm.length;i++){
attr = elm[i].getAttribute("href");//or any other kind of attribute
if(check whether should be changed){
attr = attr.replace("to be replaced", "with this");
elm[i].setAttribute("href", attr);//change the href attribute to attr
}
}