Sunday, August 2, 2009

Detect highlighted text or selected text in Firefox

This is an example of how to detect highlighted or selected text in Firefox on the current page. This can be used to detect what users on your site are looking for. This is just an example but you could easily add a little code to post the variables to a server-side script and log the information to a db, etc.

Note: This was tested on Firefox 3.0.12.


<html>
<head>
<title>foobar</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="mt.js" type="text/javascript"></script>
<!-- available from http://mootools.net/download/get/mootools-1.2.3-core-yc.js -->
<script type="text/javascript">

window.addEvent('domready', function() {
// every 3 seconds
var timer = 5;
var periodical;

var checkad = (function() {
var highlights = $$('.__mozilla-findbar-search');
var shown = false;

if($chk(highlights)) {
highlights.each(function(item, index){
if(!shown){
var text = item.get('text');
alert('Highlighted text: '+text);
shown = true;
//$clear(periodical);
}
});
}

if(window.getSelection() != ''){
alert('Selected text: ' + window.getSelection() );
//$clear(periodical);
}


});

periodical = checkad.periodical(timer * 1000, this);
});

</script>
</head>
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas risus
augue, placerat in scelerisque in, suscipit ornare purus. Donec laoreet
libero rhoncus. Aliquam id urna ante. Mauris pretium lacinia odio eget
scelerisque. Nam tempor nibh vel sapien eleifend quis iaculis mi mattis.
</p>
</body>
</html>


As a test search for one of the words on the page(such as lorem). Next use the highlight button to test.