Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep a page in firefox using javascript

Am writing an extension to provide grep'ing functionality in Firefox. At my workplace we access all log files using a browser, and grep functionality would be ideal for filtering results, looking at only particular logging levels (INFO,WARN,ERROR) etc.

Have setup the extension boilerplate.

Was wondering if I could get some hints on the required javascript. Am after a function:

function grepPage(regex){
...
}

which would apply the regex to each line in loaded text file in firefox, and change the loaded text file to only display lines that match.

This is the type of thing I could spend ages trying to work out, when I'm sure there would be simpler ways of doing this.

Any help would be highly appreciated.

Cheers, Ben

like image 485
Ben Avatar asked Mar 24 '11 06:03

Ben


1 Answers

Two ways to look at this.

One, you could avoid re-inventing the wheel: http://api.jquery.com/jQuery.grep/

Two, you could whip up a quick function (this example doesn't require jQuery or other libraries).

function grepPage(regex) {

  var lines = document.getElementByTagName('body').innerHTML.split("\n");
  var matches = new Array();

  // Check if the regex is surrounded by slashes by checking for a leading slash
  if ( ! regex.match(/^\//) ) { regex = '/' + regex + '/'; }

  for (var i = 0; i < lines.length; i++) {
    if ( regex.test( lines[i] ) ) { matches.push(lines[i]); }
  }

  // Now the 'matches' array contains all your matches, do as you will with it.

}

Warning, untested, but it should work. :)

like image 120
Rob Williams Avatar answered Sep 18 '22 14:09

Rob Williams