Tuesday, November 15, 2005

Compilling Spidermonkey on OS X

For the foreseeable future my professional life will involve a lot of messing around with browser scripting and browser simulators. Recently, I got interested in the javascript engines created by the folks at Mozilla. Turns out there is not one but two seperate engines: one called SpiderMonkey that's written in C (and used in the actual Mozilla-based browsers) and one written in Java called Rhino (used by HttpUnit among other projects).

Building SpiderMonkey on my Mac turned out to be very easy but since I couldn't find any up-to-date instructions (the README says to use CodeWarrior) I figured I'd write up a simple walkthrough.

  1. First, download the source files. I grabbed the only non-Rhino file I could find which happened to be js-1.5.tar.gz
  2. Unzip/untar the file you just downloaded
  3. Fire up Terminal.app and cd your way into the /src directory within the directory you just un-tarred.
  4. make -f Makefile.ref
  5. In a few minutes you should have a sub-directory called Darwin_DBG.OBJ
  6. Within that there's an executable called js which is the standalone javascript interpreter.

That's pretty much it. I moved the executable to /usr/local/bin but of course that's optional. You can create javascript files and run them using the js command and they just work. The one issue I haven't been able to figure out is why I can't create XmlHttpRequest objects like so var ro = new XMLHttpRequest();.

If anyone can figure that out I'd love to know what else I need to be doing.

update

I feel stupid. Of course the javascript interpreter won’t have any way to make XMLHttpRequests. All sorts of browser magic is going on in the background to make that shit happen. The network connection is the least of it. When you make an Ajax request it looks to the server just like a normal page request, complete with cookies and everything.

update 2 Feb 2007

You might want to check out this page to get a feel for what you can do in the js interpreter.

Also looks like they updated the spidermonkey tar-ball to 1.6. Here’s a page that includes the new features in 1.6. I’m a fan of the new functional constructs like map() filter() and reduce().

Once you have the interpreter up and running, try this...[1,2,3].map(function (a) { return a*2; });