Oct 11 2009

Howto: XHR Listening by a Firefox Addon

Category: Firefox, JavaScript, Pirate QuestingJonathan Fingland @ 4:00 am

The following post draws significantly from a post by Jan Odvarko at http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ but goes a bit further. There are also some sections which were inspired by Firebug, but are heavily modified.

  • What you need to know

    Before I get into the code, understand that one of the most important things in this process to understand is that your extension’s listener is just one in a chain. It is the responsibility of every listener in the chain to pass on the information. Failure to do this has some amusing consequences…. like nothing loading in the browser.

    Just to make it really clear — Don’t drop the ball. (Edit: And while you can edit the data in the stream — don’t do it unless you have a really good reason.)

  • Convenience methods and aliases

    A lot of the Firefox internals are accessed using Components.classes and Components.interfaces. While the verbosity makes it clear, it can at times be overly repetitive and, honestly, can take a long time to write out. A fairly common shorthand is in use, Cc and Ci with a few other less common shorthands like CCIN (for creating instances of a class based on a class name and an interface name) and CCSV (similarly creating a service based on a class name and interface name)

    
    if (typeof Cc == "undefined") {
    	var Cc = Components.classes;
    }
    if (typeof Ci == "undefined") {
            var Ci = Components.interfaces;
    }
    if (typeof CCIN == "undefined") {
    	function CCIN(cName, ifaceName){
    		return Cc[cName].createInstance(Ci[ifaceName]);
    	}
    }
    if (typeof CCSV == "undefined") {
    	function CCSV(cName, ifaceName){
    		if (Cc[cName])
    			// if fbs fails to load, the error can be _CC[cName] has no properties
    			return Cc[cName].getService(Ci[ifaceName]);
    		else
    			dumpError("CCSV fails for cName:" + cName);
    	};
    }
    • What’s with all of the typeof checks?

      Firebug, gotta love it, but it declares the same things using const. Inside of an if() block, a const is still seen and conflicts, even when the if condition evaluates to false. The code above is essentially a workaround to satisfy both possibilities. If the user has firebug installed, then carry on; if the user doesn’t have firebug installed, declare those shorthands

  • The constructor

    function TracingListener() {
    }

    Above is a (very) simple constructor function for us to create objects from. The methods and properties on the prototype are below. Note that while I could have changed the structure to accommodate better data-hiding, the method below reduces the number of new functions created by making them all declared only once on the prototype. Functions in the constructor are recreated every time the constructor is called with new yourConstructor() whereas functions on the prototype are shared by all instances.

  • The prototype definition

    • Basic properties

      TracingListener.prototype =
      {
          originalListener: null,
          receivedData: null,   //will be an array for incoming data.
      

      The first part of the prototype definition is setting up some basic properties. Note that both are assigned null. These properties will exist on all instances of TracingListener, and thus not be undefined if/when checking. In the case of receivedData, do not be tempted to make it an array here. Remember that methods and properties on the prototype are shared by all instances of the same type — and we don’t want all instances to share the same array for data.

      Also worth note is that receivedData is a good candidate for data-hiding and declaring it local to the constructor… but scope and visibility limitations would mean the functions requiring access to it would either need to be in the constructor as well, or have accessor and mutator methods for it. If you’re making a Singleton or a small number of instances, declaring functions in the constructor is no big deal, but this listener will be instantiated hundreds or thousands of times and it’s important to keep the duplication to a minimum.

    • Methods on the prototype

      • Interface Requirements
            //For the listener this is step 1.
            onStartRequest: function(request, context) {
            	this.receivedData = []; //initialize the array
        
        	//Pass on the onStartRequest call to the next listener in the chain -- VERY IMPORTANT
        	this.originalListener.onStartRequest(request, context);
            },

        onStartRequest is the first thing called when the actual request processing begins. This is also the best opportunity to initialize the array on this listener.

            //This is step 2. This gets called every time additional data is available
            onDataAvailable: function(request, context, inputStream, offset, count)
            {
               var binaryInputStream = CCIN("@mozilla.org/binaryinputstream;1",
                                         "nsIBinaryInputStream");
                binaryInputStream.setInputStream(inputStream);
        
                var storageStream = CCIN("@mozilla.org/storagestream;1",
                                         "nsIStorageStream");
                //8192 is the segment size in bytes, count is the maximum size of the stream in bytes
                storageStream.init(8192, count, null); 
        
        	var binaryOutputStream = CCIN("@mozilla.org/binaryoutputstream;1",
                                         "nsIBinaryOutputStream");
                binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));
        
                // Copy received data as they come.
                var data = binaryInputStream.readBytes(count);
        
                this.receivedData.push(data);
        
                binaryOutputStream.writeBytes(data, count);
        
                //Pass it on down the chain
                this.originalListener.onDataAvailable(request,
                                                  context,
                                                  storageStream.newInputStream(0),
                                                  offset,
                                                  count);
            },

        onDataAvailable essentially copies the data from the binaryInputStream to our receivedData array and to the storageStream (via the binaryOutputStream). Then we pass a new InputStream from our storageStream onto the next listener in the chain.

            onStopRequest: function(request, context, statusCode)
            {
        	try
        	{
                        //QueryInterface into HttpChannel to access originalURI and requestMethod properties
        		request.QueryInterface(Ci.nsIHttpChannel);
        
                        //this is specific to the PirateQuesting Add-on, but is left here as an example of how to modify behaviour based on the requested URL
        		if (request.originalURI
                            && piratequesting.baseURL == request.originalURI.prePath
                            && request.originalURI.path.indexOf("/index.php?ajax=") == 0)
        		{
        
        			var data = null;
        			if (request.requestMethod.toLowerCase() == "post")
        			{
        				var postText = this.readPostTextFromRequest(request, context);
        				if (postText)
        					data = ((String)(postText)).parseQuery();
        
        			}
        
                                //Combine the response into a single string
        			var responseSource = this.receivedData.join('');
        
        			//fix leading spaces bug
        			//(FM occasionally adds spaces to the beginning of their ajax responses...
                                //which breaks the XML)
        			responseSource = responseSource.replace(/^\s+(\S[\s\S]+)/, "$1");
        
                                //gets the date from the response headers on the request.
                                //For PirateQuesting this was preferred over the date on the user's machine
        			var date = Date.parse(request.getResponseHeader("Date"));
        
                                //Again a PQ specific function call, but left as an example.
                                //This just passes a string URL, the text of the response,
                                //the date, and the data in the POST request (if applicable)
        			piratequesting.ProcessRawResponse(request.originalURI.spec,
                                                       responseSource,
                                                       date,
                                                       data);
        		}
        	}
        	catch (e)
        	{
        		//standard function to dump a formatted version of the error to console
        		dumpError(e);
        	}
        	//Pass it on down the chain
        	this.originalListener.onStopRequest(request,
                                                 context,
                                                 statusCode);
            },

        The onStopRequest above has a few tricky parts. The first is the QueryInterface to nsIHttpChannel – this is critical to getting the info needed. The second tricky part is to get the posted variables. To do so, you need to check that the requestMethod was indeed post, and then we call readPostTextFromRequest which I’ll introduce in a bit. The last tricky bit is getting the Date header from the response. Date.parse() plays nicely with those (assuming the server response conforms)

            QueryInterface: function (aIID) {
                if (aIID.equals(Ci.nsIStreamListener) ||
                    aIID.equals(Ci.nsISupports)) {
                    return this;
                }
                throw Components.results.NS_NOINTERFACE;
            },

        This is pretty standard for anything fulfilling an interface contract for Firefox (or other mozilla-based browsers). QueryInterface is part of the nsISupports interface and is the only part which is scriptable. All interfaces are derived from nsISupports, so it has to be there.

      • Utility methods

        The following methods are required by our TracingListener but are not part of the interface contract. (It would also have been possible to define them globally or within a pseudo-namespace.)

            readPostTextFromRequest : function(request, context) {
                try
                {
        	        var is = request.QueryInterface(Ci.nsIUploadChannel).uploadStream;
        	        if (is)
        	        {
        	            var ss = is.QueryInterface(Ci.nsISeekableStream);
        	            var prevOffset;
        	            if (ss)
        	            {
        	                prevOffset = ss.tell();
        	                ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
        	            }
        
        	            // Read data from the stream..
        		    var charset = "UTF-8";
        		    var text = this.readFromStream(is, charset, true);
        
        	            if (ss && prevOffset == 0)
        	                ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
        
        	            return text;
        	        }
        		else {
        			dump("Failed to Query Interface for upload stream.\n");
        		}
        	    }
        	    catch(exc)
        	    {
        			dumpError(exc);
        	    }
        
        	    return null;
        	},

        I will readily admit that readPostTextFromRequest is mostly taken from Firebug, though there are a few changes. Basically, we have to do the same thing as before and QueryInterface into the appropriate interface. In this case we need nsIUploadChannel to get access to uploadStream. And then we QueryInterface the uploadStream into a nsISeekableStream (noticing a pattern, yet? QueryInterface is your best friend.. and worst enemy.). After that we store the original offset in the stream in prevOffset, and then seek to the beginning of the stream. Then we read the data and, if the stream was at position 0 originally, we seek to the beginning again.

        	readFromStream : function(stream, charset, noClose)	{
        
        	    var sis = CCSV("@mozilla.org/binaryinputstream;1",
                                    "nsIBinaryInputStream");
        	    sis.setInputStream(stream);
        
        	    var segments = [];
        	    for (var count = stream.available(); count; count = stream.available())
        	        segments.push(sis.readBytes(count));
        
        	    if (!noClose)
        	        sis.close();
        
        	    var text = segments.join("");
        	    return text;
        	}
        
        }

        readFromStream is also largely from Firebug with a few modifications. It is however remarkably similar to what is done in onDataAvailable and onStopRequest. Basically, we get a BinaryInputStream to work with the stream given. Then we loop through the segments of the stream (size provided by available()) and add them to an array. When finished with that, we join the segments and return the text.

        httpRequestObserver = {
        
        	observe: function(request, aTopic, aData){
        		if (typeof Cc == "undefined") {
        			var Cc = Components.classes;
        		}
        		if (typeof Ci == "undefined") {
        			var Ci = Components.interfaces;
        		}
        	    	if (aTopic == "http-on-examine-response") {
        	    		request.QueryInterface(Ci.nsIHttpChannel);
        
        			if (request.originalURI
                                    && piratequesting.baseURL == request.originalURI.prePath
                                    && request.originalURI.path.indexOf("/index.php?ajax=") == 0) {
        				var newListener = new TracingListener();
            				request.QueryInterface(Ci.nsITraceableChannel);
            				newListener.originalListener = request.setNewListener(newListener);
        			}
        		}
        	},
        
        	QueryInterface: function(aIID){
        		if (typeof Cc == "undefined") {
        			var Cc = Components.classes;
        		}
        		if (typeof Ci == "undefined") {
        			var Ci = Components.interfaces;
        		}
        		if (aIID.equals(Ci.nsIObserver) ||
        		aIID.equals(Ci.nsISupports)) {
        			return this;
        		}
        
        		throw Components.results.NS_NOINTERFACE;
        
        	},
        };

        This part is fairly straightforward. The object httpRequestObserver has to fulfill the contract for the nsIObserver interface — which only has two methods: observe and QueryInterface.

  • Observer registration

    Finally, we need to register the observer:

    var observerService = Cc["@mozilla.org/observer-service;1"]
        .getService(Ci.nsIObserverService);
    
    observerService.addObserver(httpRequestObserver,
        "http-on-examine-response", false);

    Now the observerService will call the observe method on httpRequestObserver whenever it notifies observers with the http-on-examine-response topic.

    When you want to unregister the observer, use:

    observerService.removeObserver(httpRequestObserver,
        "http-on-examine-response");

    As you can see, getting the text and post variables from an http request is non-trivial.

Note, though, that this code does not check the context to determine whether the http request is for a browser window, or from a browser window so depending on the complexity of your situation, you may want to do that as well. Perhaps, I’ll add that in another post.

(See Firebug license here. Special thanks to the Firebug team and to Jon Odvarko for providing so much useful material. The interface docs at oxymoronical are a great resource. The Mozilla Developer Center also deserves special credit for great documentation. )

Update (Jan 17, 2010): Corrected a small bug in onStopRequest (Thanks Broady!). See below for details.

Update (April 22, 2010): Corrected a bug which doesn’t occur if Firebug is installed (Thanks Harini!). See below for details.

Tags: , , ,


Oct 09 2009

Implementing an XPCOM Firefox Interface and Creating Observers

Category: Firefox, JavaScriptJonathan Fingland @ 4:05 am

There are lots of cases when it is desirable to implement one of the XPCOM interfaces in use by Firefox, or other mozilla-based browsers. There are three cases where PirateQuesting does so, but once you see the concept, it should be easy to adapt to your situation.

  • You must have a QueryInterface to enjoy this ride

    First off, all XPCOM interfaces in Firefox inherit from nsISupports (Also see details on oxymoronical.com here). Only one method is scriptable and part of XPCOM — QueryInterface — and it must be present in all implementations of XPCOM interfaces.

    
    //"implements" nsISupports
    var InterfaceImplementation = function() {
      QueryInterface: function (aIID) {
          if (aIID.equals(Components.interfaces.nsISupports))
          {
             return this;
          }
          throw Components.results.NS_NOINTERFACE;
      }
    }
    

    The above is an example of the very minimum required to support any interface. QueryInterface requires a first parameter which is an aIID from Components.interfaces.*. There is also a second, optional, parameter, but as I have never come across this in use, it’s not worth pursuing here.

  • Now what?

    A very common (and useful) use of XPCOM interface implementation is creating your own observers, for example:

    
    var myObserver = {
    
      observe: function(request, aTopic, aData){
        if (aTopic == "http-on-examine-response")
        {
          //response has come back, now what?
        }
        else if (aTopic == "http-on-modify-request")
        {
          //opportunity to modify headers on request
        }
      },
    
      QueryInterface: function(aIID){
         if (aIID.equals(Components.interfaces.nsIObserver) ||
             aIID.equals(Components.interfaces.nsISupports))
        {
          return this;
        }
        throw Components.results.NS_NOINTERFACE;
      },
    };
    

    The nsIObserver interface is fairly simple as it only adds one new method. As you can see now, though, QueryInterface now checks for both nsIObserver and nsISupports. Remember: any interface you implement must have a QueryInterface supporting all interfaces in the inheritance chain.

  • Observer registration

    If you then wanted to register your observer, it’s as easy as:

    
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
                                   .getService(Components.interfaces.nsIObserverService);
    
    observerService.addObserver(myObserver,"http-on-examine-response", false);
    observerService.addObserver(myObserver,"http-on-modify-request", false);
    

    Then to unregister, you do:

    
    observerService.removeObserver(myObserver, "http-on-examine-response");
    observerService.removeObserver(myObserver, "http-on-modify-request");
    

    When I have a chance, I’ll add a more complete example of using observers to watch http requests, but in the meantime check out the list of Observer Notifications at MDC.

Tags: , ,


Sep 24 2009

Singletons in JavaScript

Category: JavaScript, PHPJonathan Fingland @ 4:13 pm

I use singletons all over the PirateQuesting code, but I’ve never explained the idea here, nor how they are different from singletons in other languages.

Anyone familiar with common design patterns knows how singletons work in the vast majority of languages. For a PHP example, see this post.

In JavaScript there are basically two main ways to create a singleton. One is use immediate instantiation so that the class may not be instantiated again. The second is closer to the traditional singleton pattern, however, since there are no private members or constructors, we can get around this by using a nested ‘class’ constructor — and there are two ways to accomplish this.

The first way is done as follows:

var singleton = new (function Singleton() {
                               this.value = 12;
                             } )();

alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not defined.

alert(singleton instanceof Singleton); // Singleton is not defined

In the above, the constructor name, Singleton, isn’t really necessary. While it can’t be used to instantiate the Singleton again, it also can’t be used with instanceof or typeof so feel free to leave it out if you want; leaving it in, does make it more obvious what is happening though.

And the second way (version 1):

var Singleton = (function () {
  var instance = null;

  function Singleton() {
    this.value = 12;
  }

  this.getInstance = function () {
    if (instance === null) {
      instance = new Singleton();
    }
    return instance;
  }
})();

var singleton = Singleton.getInstance();
alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not a construct

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton

The above is just an anonymous function being called immediately (note the () after the function declaration). Inside the function it declares a pseudo-private member called instance, a pseudo-private constructor, Singleton, and a getInstance method. The getInstance method can see instance due to closure, while the outside world has no idea that it exists.

And finally, the second way (version 2):

var Singleton = {

  getInstance : (function() {

    var instance;
    function Singleton() {
      this.value = 12;
    }

    return function () {
      if (instance == null) {
	    instance = new Singleton();
      }
      return instance;

    }

  })()
}

var singleton = Singleton.getInstance();
alert(singleton.value);

var singly = new Singleton(); // Singleton is not a constructor

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton

In this final example, all of the logic is put into the getInstance function which is the result of a self-calling function which itself returns a function. Yeah, it’s a little hard to follow, but basically the returned function has visibility of instance and the Singleton constructor due to closure.

As a closing note, it’s worth pointing out that although all of the above methods do not permit a second instance construction, they also do not allow use of typeof or instanceof for type verification.

Update

Based on a comment below by Peter Robinett, I’ve come up with a different way to do this, which allows for instanceof and typeof and seems to be an all-round good solution to the problem. It does not, however use the classical getInstance method, but works well all the same.

var Singleton = function () {
  var instantiated = false;

  return function () {
    if (instantiated) {
      throw "Singleton already instantiated";
    }
    instantiated = true;
    this.value=12;
    }
}()

var singleton = new Singleton();
alert(singleton.value);    //alerts 12
alert(singleton instanceof Singleton);  alerts true 

var singly = new Singelton(); //throws exception and cannot be instantiated

Tags: , ,


Dec 01 2008

Functions in Closures

Category: DOM, JavaScriptJonathan Fingland @ 7:47 am

I last wrote about closures and how this affects the visibility of variables and functions. This time I’m going to introduce returning functions from a closure and how it can be useful in the first part.

First off, lets say you have a strange need to create functions to consistently add a value like addFive, addTen, etc. Well this is one way to go about it.

function createAdder(addition_size) {
      return function (value) {
                     return value + addition_size;
               }
}

var addFive = createAdder(5);
var addTen = createAdder(10);

alert(addFive(3));
alert(addTen(-10));

The code above will alert 8 and 0. While this isn’t the most natural use of the technique, hopefully it is clear enough. addition_size is retained by the addFive and addTen functions because the function had visibility when it was declared.

One handy way to use this is when creating event handlers that need to take parameters. When adding a handler, you pass the function itself, which doesn’t provide an opportunity to add extra parameters, we can get around this by doing:

function getValuePlusFiveDisplayer(value) {
  return function (event) {
    var sum = addFive(value);
    alert(value + " + 5 = " + sum);
  }
}

var number_1 = document.getElementById("number_1");
number_1.addEventListener("click",getValuePlusFiveDisplayer(1),false);

var number_2 = document.getElementById("number_2");
number_2.addEventListener("click",getValuePlusFiveDisplayer(2),false);

And HTML like:

<span id="number_1" class="number_button">1</span>
<span id="number_2" class="number_button">2</span>

Which would work like this:

12

Even though you’re unlikely to need this exact example, hopefully it gives you some ideas, or helps solve some problems

Tags: ,


Oct 26 2008

Passing parameters into a created dialog, and retrieving them on exit

Category: DOM, Firefox, JavaScript, Pirate Questing, XULJonathan Fingland @ 7:50 am

This is going to be a pretty short tutorial today to help explain how to pass information to an window when opening it. The following is taken from PirateQuesting.

First, here is the function for entering the code when PirateQuest asks the user for verification.

function enterCode(url,imgsrc, func) {
	var params = {in:imgsrc, out:null};
	window.openDialog("chrome://piratequesting/content/codeDialog.xul", "",
		"chrome, dialog, modal, resizable=no, status=no,
		height=250, width=400", params).focus();
	if (params.out) {
		piratequesting.Code.submit(url,params.out,imgsrc,func);
	}
	else {
	    // User clicked cancel. stop here
	}
}

So, as we can see in the first line the params variable stores a hash. A has is useful here as it allows us to easily pass more than one variable in without goign to the work of creating an object. There are actually much more significant differences between a hash and an object but, for this tutorial, know that it stores values in name:value pairs separated by commas and all of it enclosed by curly braces. The last element must not be followed by a comma.

Next, when we use openDialog we pass params into the dialog.

After the user has clicked OK, the value of params.out is checked. The condition will be true unless the value is still null or by some strange miracle taken on a value like ‘false’.

Now, let’s look at the code behind the dialog itself

function codeDialogOnLoad() {

    // Use the arguments passed to us by the caller
    document.getElementById("codeImage").setAttribute('src',
            window.arguments[0].in);
}

// Called once if and only if the user clicks OK
function onOK() {
    window.arguments[0].out = document.getElementById("codeValue").value;
    return true;
}

Ok, so what do we have here? well, when the dialog first loads we call codeDialogOnLoad which then sets the image source on the dialog based on the value passed in params.in. Note that it is now referred to as window.arguments[0].in.

When the user presses OK, the value of an input box, codeValue, is assigned to params.out (a.k.a. window.arguments[0].out).

Last thing to look at is the codeDialog.xul

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?>
<dialog
  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  id="codeDialog"
  title="Enter the Code"
  ondialogaccept="return onOK();"
  buttonlabelaccept="Submit"
  onload="codeDialogOnLoad();"
  persist="screenX screenY width height">

	<script type="application/x-javascript" src="chrome://piratequesting/content/codeDialog.js"/>
	<vbox>
		<label value="Enter the code shown below" />
		<image id="codeImage" />
		<textbox width="50" id="codeValue" />
	</vbox>
</dialog>

As you can see, codeDialog.xul is very simple and contains only three elements inside a vbox. This is really one of the simplest examples you could use and was chosen to illustrate how to simply and easily pass information into and out of a dialog

Tags: , , , ,


Aug 14 2008

Dynamically Generated and Updated Table

Category: CSS, DOM, JavaScriptJonathan Fingland @ 12:21 am

Although the page itself is pretty bare bones, the script itself is even simpler.  The bandanna guide is another piece I wrote to accompany the game Pirate Quest.

This article attempts to demonstrate how we can use dynamically generated DOM objects to update table data on the fly.  In this case it’s fairly simple as only one value is changing and we’re only changing the cell text. There are some other ideas demonstrated here, such as using opacity and alternating row styles to create a colourful and easy to read table.

The following is the table we’ll be updating. It’s pretty simple – just the column headings.  EDIT: added thead and tbody tags. IE would append rows to the table unless they were in the tbody tag.

<table id="tbl_guide" border="1">
	<thead>
		<tr>
			<td rowspan="2">Level</td>
			<td rowspan="2">Energy</td>
			<td colspan="2">No Bandanna</td>
			<td colspan="2">Bandanna of Vigor</td>
			<td colspan="2">Bandanna of Vitality</td>
			<td colspan="2">Bafunda de la Cabeza</td>
		</tr>
		<tr>
			<td>min</td>
			<td>max</td>
			<td>min</td>
			<td>max</td>
			<td>min</td>
			<td>max</td>
			<td>min</td>
			<td>max</td>
		</tr>
	</thead>
	<tbody id="tbl_body"/>
</table>

You can use whatever you want to start the update process. In this case I used the onchange event on a drop down list

<select id="hideout" onchange="update(Number(this.options[this.selectedIndex].value));">
  <option value="100">homeless (100)</option>
  <option value="105">Wretched Alcove (105)</option>
  <option value="110">Abandoned Outhouse (110)</option>
  <option value="115">Festering Swamp (115)</option>
  <option value="120">Swamp with a View (120)</option>
  <option value="130">Desolate Beach (130)</option>
  <option value="140">Rundown Shanty (140)</option>
  <option value="150">Rusted Roof Shack (150)</option>
  <option value="160">Shanty with a Fence (160)</option>
  <option value="170">Deserted Manor (170)</option>
  <option value="180">Ruined Castle (180)</option>
  <option value="185">Rundown Castle (185)</option>
  <option value="190">Stronghold (190)</option>
  <option value="195">Fortified Stronghold (195)</option>
  <option value="200">Shack on Skull Island (200)</option>
  <option value="220">Cavern on Skull Island (220)</option>
  <option value="230">Stronghold on Skull Island (230)</option>
</select>

Next, on to the script itself. First we define the number of rows and columns, and we create a 2D array for our cells.

//2D array of table cells
var cells = new Array();

var numcols = 10;
var numrows = 600;

I used the body onload event to set up the table rows. EDIT: Because IE doesn’t seem to recognize a class or style change made with setAttribute(), I had to fall back on an alternative

function onLoad() {
	//get our table and our select box
	var table = document.getElementById("tbl_guide");
	var select = document.getElementById("hideout");
	var row; //tr DOM object
	var cell; //td DOM object
	var celltext; //createTextNode DOM object
	var row_arr; //array of cells for each row
	//for the opacity overlay we use three divs. one on the outside, one for the
	//background color and one for the text
	var out_div, in_div1, in_div2; 

	//loop through the number of rows we want
	for (var i = 0; i<numrows; i++) {

		//create this row and set the style for even or odd.
		row = document.createElement("tr");
		row.setAttribute("class",(i%2 == 0)? "even":"odd");
		row.className = (i%2 == 0)? "even":"odd"; //for IE

		//get a new, clean array to work with
		row_arr = new Array();

		//loop through each cell for the number of columns we have
		for (var j=0; j<numcols;j++) {

			//create our table cell and div arrangement for our opacity trick
			cell = document.createElement("td");
			out_div = document.createElement("div");
			in_div1 = document.createElement("div");
			in_div2 = document.createElement("div");

			//set the styles for the div objects
			out_div.setAttribute("class","outer");
			in_div2.setAttribute("class","text");
			in_div1.setAttribute("class","bg");

			//for IE (up to 7) since it appears to lack proper support for setAttribute
			out_div.className = "outer";
			in_div1.className = "bg";
			in_div2.className = "text";

			//depending on what cell we're in we should do different things. mostly this affects the styles
			switch(j) {
				case 0:
					//level
					celltext = document.createTextNode(String(i+1));
					in_div1.setAttribute("style","background-color:yellow;");
					in_div1.style.background = "yellow"; //for IE again
					break;
				case 1:
					//Energy
					celltext = document.createTextNode(String(i+10));
					in_div1.setAttribute("style","background-color:yellow;");
					in_div1.style.background = "yellow";
					break;
				case 2:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:red;");
					in_div1.style.background = "red";
					break;
				case 3:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:red;");
					in_div1.style.background = "red";
					break;
				case 4:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:blue;");
					in_div1.style.background = "blue";
					break;
				case 5:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:blue;");
					in_div1.style.background = "blue";
					break;
				case 6:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:green;");
					in_div1.style.background = "green";
					break;
				case 7:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:green;");
					in_div1.style.background = "green";
					break;
				case 8:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:purple;");
					in_div1.style.background = "purple";
					break;
				case 9:
					celltext = document.createTextNode("");
					in_div1.setAttribute("style","background-color:purple;");
					in_div1.style.background = "purple";
					break;
			}

			//add our text to the second inner div
			in_div2.appendChild(celltext);

			//append the two inner divs to the outer div, then append the outer div to the cell
			out_div.appendChild(in_div1);
			out_div.appendChild(in_div2);
			cell.appendChild(out_div);

			//append the cell to the row
			row.appendChild(cell);

			/* finally add this celltext to the row array.
			 * NOTE: you could just as easily append one of the divs or the td tag. In this case
			 * I'm only changing the text. If you wanted to change the colors, for example, you'd
			 * need to push in_div1 onto the array. To change both the color and the text\, you'd
			 * need to push out_div onto the array and later access the children
			 */
			row_arr.push(celltext);
		}

		//add the row to the table, and push the row array onto our 2d cell array
		table.appendChild(row);
		cells.push(row_arr);
	}
	/* then update the values. The operation performed in update() could have been included
	 * in the switch-case above, but then if I changed it, I'd need to change it in two places.
	 * Casts the value from the select box to Number. for *, / , etc. the value is interpreted as
	 * a number anyways, but for +, it assumes it's a string value.... so we have to cast it.
	 */
	update(Number(select.options[select.selectedIndex].value));
}

The onLoad function only assigns values to level and energy.  Hopefully the comments in the code are clear enough to see what I’ve done.

Next up, the update function

function update(value) {
	//loop through each row
	for (var i = 0; i<numrows; i++) {
		//loop through each cell in a row but ignore the first two
		//(values were set up in the onLoad and don't change now)
		for (var j=2; j<numcols;j++) {
			//again switch-case, this time for the different formulas in each cell
			switch(j) {
				case 2:
					//no bandanna min
					cells[i][j].nodeValue = tp((value/150) * ((i+10)/20));
					break;
				case 3:
					//no bandanna max
					cells[i][j].nodeValue = tp((value/75) * ((i+10)/20));
					break;
				case 4:
					//vigor min
					cells[i][j].nodeValue = tp((value/150) * ((i+20)/20));
					break;
				case 5:
					//vigor max
					cells[i][j].nodeValue = tp((value/75) * ((i+20)/20));
					break;
				case 6:
					//vitality min
					cells[i][j].nodeValue = tp(((value + 20)/150) * ((i+10)/20));
					break;
				case 7:
					//vitality max
					cells[i][j].nodeValue = tp(((value + 20)/75) * ((i+10)/20));
					break;
				case 8:
					//bafunda min
					cells[i][j].nodeValue = tp(((value + 25)/150) * ((i+25)/20));
					break;
				case 9:
					//bafunda max
					cells[i][j].nodeValue = tp(((value + 25)/75) * ((i+25)/20));
					break;
			}
		}
	}
}

The update function, as you can see, is very simple. we use .nodeValue to change the text content of our text nodes. As noted in the comments of the onLoad, you could also use the cell itself or one of the containing divs. Your cases would look more like cells[i][j].childNodes[1].childNodes[0].nodeValue if you used out_div in your cells array.

I suppose the last thing to look at is the style section.

table { border-collapse:collapse; border-width:3px; border-style:double; border-color:black; }
td { border-color:black; border-width:1px; }
thead tr td {  padding-left:.5em; }
tbody tr td { padding: 0px 0px 0px 0px; height:1em; width:5em; }
div.outer { position:relative;}
div.bg { opacity: 0.3; height:1em; filter: alpha(opacity=30); padding: 5px 10px 5px 10px; }
div.text { position: absolute; top: 0; bottom: 0; color: black; padding: 5px 10px 5px 10px; }
tbody tr.even { background-color:#d0d0d0; }
tbody tr.odd { background-color:#ffffff; }

It’s pretty short. True, I could have done more to pretty up the page.. and I may yet. but for now, it works well enough and demonstrates the dynamic generation and update technique.

As you can see the code is far from complicated and this would have been far messier in the old pre-DOM days *shudder*.


EDIT: Also, please note that in IE the page is so slow to generate and update that I develop a whole new loathing for Ie every time I open it. In firefox, the generation takes a little time, but not too bad. The updating in Firefox is quite quick. For a small set of rows, IE is fine… 600 rows seemsto kill it though.

Tags: , , , , , ,


Aug 13 2008

Pirate Questing

Category: DOM, Firefox, JavaScript, Pirate Questing, XULJonathan Fingland @ 5:24 am

Pirate Questing is a firefox addon thatI’ve been devloping for a while. It’s available at AMO here

I’ll mostly be using this space to document interesting solutions I come across.

Tags: , ,