Blogger Hack - Highlight Search Words

Nearly 2 months since I started this blog and finally I have started getting some organic page views through google. So I created a blogger hack which highlights the search words whenever somebody visits the page through google search. Its not highly tested and major work needs to be done on finding the search words from referring URL. The limitations are

  • Currently supports only google search (includes google blog search). Though I saw that basic difference between yahoo and google is usage of p instead of q for the query input.
  • Parsing search words supports only basic type of queries. It does not supports queries with quotes(just found this one) or any other specialized searches. I am searching for already written code for this.
  • Although it supports only blogger, it should be easy to modify. Change would be the way it gets the post body elements.
Here is the code. I will have to see how to avoid the br in the text area. Also how to show the script tags. As blogger gave warning I had to remove.


<style>
.highlighted {
background-color :#FFFF00
}
>/style<

<script>
function goDeep( node) {

if (node.nodeName == 'a' ||
node.nodeName == 'img' ||
node.nodeName == 'BR' ) {
return;
}
if ( node.nodeName == '#text') {
if ( node.parentNode.className == 'highlighted' ) {
return;
}
processTextNode(node);

} else {
for(var i=0; i < node.childNodes.length; i++) {
goDeep(node.childNodes[i]);
}
}
}
function wholefunc() {

if (!document.referrer ) {
return;
}

var url = document.referrer;

var isGoogle = url.match("google");
var qStrs;
if ( isGoogle == "google" ) {
var qReg = new RegExp("q=[\\w\+]+","i");
var qMatch = url.match(qReg);
qStrs = qMatch[0].substring(2,qMatch[0].length).split("\+");
}
if (qStrs == null) {
return;
}

var mStr = qStrs[0];
for(var i=1; i < qStrs.length ; i++) {
mStr += '|'+qStrs[i];
}

mReg = new RegExp(mStr,"ig");

var allDivs = document.getElementsByTagName('div');
for(var i=0; i < allDivs.length; i++) {
if ( allDivs[i].className == 'post-body') {
for(var j=0; j < allDivs[i].childNodes.length; j++){
goDeep(allDivs[i].childNodes[j]);
}
}
} // All div loop
} // end of whole func

function processTextNode (currNode) {

matches = currNode.nodeValue.match(mReg)

while( matches != null ) {
var sNode = currNode.splitText(currNode.nodeValue.indexOf(matches[0]));
var tNode = sNode.splitText(matches[0].length);
var felm = document.createElement('font');
felm.className = 'highlighted';
felm.appendChild(sNode);
currNode.parentNode.insertBefore(felm,tNode);
matches = tNode.nodeValue.match(mReg);
currNode = tNode;
}

}
var mReg;
wholefunc();
</script>

0 Comments: