@Chromium Team: please provide usable error messages

Reorganizing a project I rewrote a part that previously included a source file via a script file to include it via XMLHttpRequest and BOOM, my code suddenly imploded on Chrome during local testing.

What’s so bad about it is that it imploded with a cryptic error message “XMLHttpRequest Exception 101” which means a NETWORK_ERR has occured(a fairly broad error state that basically covers everything that has to do with loading).

I figured that this could be a security restriction and was able to find the appropriate bug #37586, but really: you don’t want to have your developers jumping through such hoops just to find out what an error message means. A simple error description such as “Security Error: Document may not request data from file:// protocol” would have spared me and probably a lot of other people a lot of searching.

In case you’ve encountered the same issue: The solution is to disable file:// protocol restrictions with the –allow-file-access-from-files command line switch.

A pattern for Javascript OOP that I actually use

Apparently a few people were pretty irritated the last time I posted about what you can make Javascript do (+foo instead of foo() for calls) so today I thought I’d post about a pattern that I actually use regularly. Of course, as with any pattern there are good reasons not to use it. Most of all:complexity… for example you may not be able to make your favourite development environment understand it. Speed shouldn’t be an issue though: It adds one entry to the name lookup tree, but that shouldn’t even really be measurable.

When you do OOP Javascript you’ll often want to add a lot of stuff to the prototype of a constructor. Often people use object notation to get around having to type Foo.prototype.bar=… over and over again. Problem is: This replaces the prototype, so if you’re using inheritance it won’t work. You’d overwrite the inherited prototype:

var BaseCtor=function(){};

var FailedInheritanceCtor=function(){};
FailedInheritanceCtor.prototype=new BaseCtor;
FailedInheritanceCtor.prototype={
   foo:0,
   bar:1
};

alert((new FailedInheritanceCtor) instanceof BaseCtor); //false

var WorkingCtor=function(){};
WorkingCtor.prototype=new BaseCtor;
WorkingCtor.prototype.foo=0;
WorkingCtor.prototype.bar=1;

alert((new WorkingCtor) instanceof BaseCtor); //true

So, you need to do assignments. Of course you could use a function to do them, but that’s one more unnecessary and ugly function call. Or you could use a temporary variable to point to the prototype… but unless you can use Javascript 1.7’s “let” statement that would mean contaminating the current scope. You could wrap it into an anonymous function, but that hardly improves readability.

All of this can be avoided by using the poor man’s “let” (or poor browser’s: your choice): with()
With pushes an object into the name lookup tree… the nice thing is that this object can be created right inside that statement

with({hello:"world"})
   alert(hello); //world

And we can do the same stupid trick with the prototype property:

var BaseCtor=function(){};

var WorkingCtor=function(){};
WorkingCtor.prototype=new BaseCtor;
with({_:WorkingCtor.prototype}){
   _.foo=0;
   _.bar=1;
}

or like this if you want it more compact (I never do that though):

var BaseCtor=function(){};

var WorkingCtor=function(){};
with({_:WorkingCtor.prototype=new BaseCtor}){
   _.foo=0;
   _.bar=1;
}

There. simple. I usually combine it with a variable _ inside the methods to get to this, but that may feel wrong to you.

var BaseCtor=function(){
   var _=this;
};

var WorkingCtor=function(argFoo){
   var _=this;

   _.foo=argFoo;
};
WorkingCtor.prototype=new BaseCtor;
with({_:WorkingCtor.prototype}){
   _.foo=0;
   _.bar=function(argFoo){
      var _=this;

      alert(_.foo);
   };
}

(new WorkingCtor(1)).bar(); //1

Offering Bookmarklets with icons

Update: This doesn’t work as intended anymore. A new article offering an alternative method that works for modern Firefox versions has been posted here.

Note: this is tested only in Firefox. It works perfectly there, but in other browsers you may either get the icon only temporary (if the bookmark icon cache is part of the normal cache) or no icon at all. However it won’t break anything anywhere, so that’s no reason to not use it.

I investigated this a while back and it’s really quite simple, but apparently few people are aware of it:

First of all (in case you don’t know what a bookmarklet is): Bookmarklets are tiny Javascript programs that you store in Bookmarks which when you open the bookmark will run on whatever page you are currently viewing… for example copying a snippet from an article and pasting it into your blog or highlighting images or … well just about anything that a website can do. Pretty much any popular site (Google, Facebook, …) offers bookmarks for various purposes.

The problem is that apparently very few Bookmarklet developers know how to provide icons. Hopefully my little post can change that at least a bit 🙂

It’s really quite simple: Bookmarklets usually have this form:

javascript:alert(“My functionality”);void(0);

Most people put that void(0); there automatically, but it’s important to realize what it actually does: It prevents the code from returning anything. Why do we do that? Because otherwise we’d trigger another behaviour of javascript: urls. Something that I usually like to call “poor man’s data: urls”. You see, anything a javascript url call returns is processed as HTML. So javascript:”<!DOCTYPE html><html><head><title>Hello World</title></head><body>Hello World</body></html>”; actually sends you to a HTML document.

So, let’s recap: A javascript: url can either be a bookmarklet or a document. Well, that’s not quite correct, it’s actually always both, we just use one of these functions at a time. We can actually have both at the same time in various ways, the one that’s most important in our case is that we want the javascript: url to behave like a document when the user clicks in on the webpage, but like a bookmarklet after the user has added it as one. The reason being that documents can have icons. And since the url will be identical, so will the bookmarklet.

So first set up a document javascript: url with an icon:

javascript:'<!DOCTYPE html><html><head><title>Hello World</title><link rel=”icon” type=”image/png” href=”http://www.tapper-ware.net/devel/js/JS.Bookmarklets/icons/next.png” /></head><body>Hello World</body></html>’;

Go ahead, click it 🙂 . You’ll see a nice little play button as icon. Drag the title bar onto the bookmarks toolbar and you’ll see that it retains the icon and as an added bonus the title. Don’t worry about the HTML code bloating up your Bookmarklet, we won’t have to include it directly in the final version, but it’s easier to understand this way.

So, now we need a branch so that it will show the content only when clicked on the original page. Again, there are different ways, for now we’ll just stick with the easiest one of checking for a variable that we are reasonably sure will only exist on the original page:

javascript:window[‘bm.dummy@tapper-ware.net’]=true;void(0);

javascript:if(window[‘bm.dummy@tapper-ware.net’]){ ‘<!DOCTYPE html><html><body>My document</body></html>’; }else{ alert(‘My functionality’); void(0); }

Now, we only need the document content if the variable exists, so we can use it to transport the content instead of including it literally in the bookmarklet, bringing the size of the Bookmarklet down dramatically and freeing us from the requirement to have really compact HTML:

javascript:window[‘bm.dummy@tapper-ware.net’]='<!DOCTYPE html><html><body>My document</body></html>’;void(0);

javascript:var bmi=window[‘bm.dummy@tapper-ware.net’]; if(bmi) bmi; else{ alert(‘My functionality’); void(0); }

You could of course also introduce some randomness into the id if you’re afraid websites will try to block it, I’ll leave that up to you.

At the end of the day, you’re whole bookmarklet could then look something like this:

javascript:

var id=’bm.next.’+((Math.random()*9999)|0)+’@tapper-ware.net’;

window[id]='<!DOCTYPE html><html><head><title>Next</title><link rel=”icon” type=”image/png” href=”http://www.tapper-ware.net/devel/js/JS.Bookmarklets/icons/next.png” /></head><body>This is a bookmarklet. Drag its tab to your bookmarks toolbar to add it. Click the resulting button on any page to automatically find links containing the word next</body></html>’;

document.location=’javascript: if(window[“‘+id+'”]){window[“‘+id+'”]; }else{ (function(){ var f=function(e){ return !!(/next/i).exec(e.textContent)}; var l=document.querySelectorAll(“a”); for(var i=0;i<l.length;i++) if(f(l[i])) document.location=l[i].href; })(); void(0); }’;

void(0);

There are numerous way to automate this or make it prettier, but I’ll leave that to you. So long 🙂

Javascript in the commandline

I don’t know for how long a little script has been running on my computer to keep me sane in the Windows driveletter jungle.

These days I work almost exclusively on Windows because frankly it fits my daily usage patterns best… that doesn’t mean it’s a perfect fit, but with a combination of Cygwin and a few dozens other tools as well as a Linux-like directory setup I can retain at least most of my sanity.

One very important tool in the way I organize my system are symlinks or more specifically junctions (they provide roughly the same functionality as Windows symlinks, but Windows doesn’t try to translate them to their target path when an application requests something inside).

For example if you want to find one of my external harddisks you’ll find it under \media\WD2000 which is a junction pointing to the drive’s root folder.

Theoretically you can do this without any junctions by setting that drive as a virtual folder. Problem is: Windows gets confused if you regularly change your external drives. Even more so if TrueCrypt is involved.

So I decided to use the junctions approach and write a little shell script to update the junctions automatically. FSUtil provides all the needed functionality, so it seemed simple enough. At least until I tried to do the necessary string processing using the Windows shell. Urgh. In short: Don’t even try. Whatever you try to do, it won’t work.

Luckily I had a Spidermonkey build at hand (js.exe) and while the Spidermonkey JS shell isn’t intended for shell scripting, it can handle STDIN and STDOUT which is really all you need. js.exe is now also part of XULRunner builds, so you can easily grab it from ftp://ftp.mozilla.org/pub/xulrunner/nightly/

Yes, I could have used dozens of other solutions. SED, WScript: but all of them would have required me to learn their syntax when I didn’t really want to. I just wanted to do string processing and I kinda felt that if I knew probably the best-known language for string processing, I shouldn’t have to learn another one for the same purpose.

What you do if you want to use JS for string processing, is make it part of a pipe chain, like this:

js -e “main=’f1′;” %0|cmd /K|js -e “main=’f2′;” %0|cmd /K

That looks worse than it actually is, it just means:
run js.exe (with main set to f1 and the cmd file loaded as js) output through cmd.exe
send cmd.exe output to js.exe (with main set to f2 and the cmd file loaded as js)
run js.exe (with main set to f2 and the cmd file loaded as js) output through cmd.exe

…you get the idea: You just alternate between js.exe and cmd.exe, each operating on the previous one’s output.

The only real pitfall is that your cmd file is both a cmd file and a js file at the same time, but that’s pretty easy to overcome:

REM = 0; /*
@echo off
cls
[[SHELL_CODE]]
goto :END
REM ; */
[[JS_CODE]]
REM ; /*
:END
REM ; */

Again: it looks worse than it is: You simply use JS comments to make js.exe ignore the shell code (you need a few dummy REM statements as well), while using a mixture of Shell comments and jump statements to make cmd.exe skip over the JS code.

And that’s pretty much it. Other then that you only really need to know that in order to read something from STDIN with js.exe you call readline() until it returns null and print(“foo”) to output “foo\n” (including a newline character).

Throw in something like this and you can call different functions directly;

var lines=[];
var line;
while(null!=(line=readline())) lines.push(line);
this[main](lines);

with
js -e “main='[[function name]]’;” %0

And finally, here’s the script file that I’m using to keep my junctions up to date:
http://www.tapper-ware.net/devel/js/js.shellJunctionUpdates/readyDriveList.js.cmd
It basically checks for a file \.mountpoint on every drive and creates a junction to that drive in the location specified inside the .mountpoint file (liek this: MOUNTPOINT=C:\media\WD2000)

Firefox loading times: beware of FlashGot

A while ago, I was discussing the startup time of Firefox with a few friends and it became apparent that we got very different results: For me, a Firefox cold start took between 0.3 and 0.7 seconds, compared to about 4 seconds for everybody else. All of us had a bunch of Addons installed (12 in my case), so it wasn’t exactly the amount of Addons that was causing it.

After some experimenting we found that in every single case the launch time got down to below one second if FlashGot (which I had deactivated for some reason that I can’t even remember) was disabled.

That doesn’t make FlashGot a bad addon, but you should be aware that startup time increases dramatically.

Current Mozilla Fennec / Firefox Mobile builds on Windows

Aside from my main work machine I own a tiny Acer Netbook. It’s not the best device around with limited processing power and much more importantly, a 1024×600 screen. Using Firefox on it isn’t exactly a joy because you often get horizontal scroll bars and the vertical size of the content is tiny if you have the title bar, the navigation bar and the tabbar open (even with bookmarks-toolbar and menubar disabled).

Some time ago I tried using Fennec and while it’s definitely not perfect, the way zoom and scrolling is handled alone makes it the better alternative for touchpads and tiny screens. In Fennec you drag to scroll (which with your off the mill Synaptics touchpad means double-tap, then move) and double-tap without moving to zoom in on a paragraph (which really is immensely useful if your screen is too small to fit a whole lot of text onto it without making it so tiny that it’s hard to read). Besides, all UI-elements are hidden unless you scroll to them (tabs on the left, settings on the right, location at the top).

When Fennec was first released, there were a couple of Win32 builds available, but apparently support for Windows was dropped with the release of the 1.0 version.

Luckily, you can still use it on Windows, courtesy of Mozilla’s XULRunner platform which Fennec uses internally: Just grab a recent Fennec Linux build, drop in a recent XULRunner build for Windows, edit the application.ini to allow for newer versions of XULRunner and you’re set.

Grab a normal Linux build from
ftp://ftp.mozilla.org/pub/mobile/nightly/latest-mobile-trunk/
(currently that’s fennec-1.1a2pre.en-US.linux-i686.tar.bz2)

And a XULRunner runtime from
ftp://ftp.mozilla.org/pub/xulrunner/nightly/latest-trunk/
(currently that’s xulrunner-1.9.3a4pre.en-US.win32.zip)

Extract the Linux Fennec built somewhere and remove the xulrunner directory.

Then, drop the xulrunner win32 runtime in its place (you can also remove the shell scripts).

Take the xulrunner-stub.exe from the xulrunner directory and drop it into the main Fennec directory. You can name it any way you like (mine is simply called Fennec.exe). You’ll need mozcrt19.dll DLL as well, just copy it along.

If you get an error about XULRunner being the wrong version, just open application.ini in a text editor and change MaxVersion to reflect the version you use.

And that’s it: Now you’ve got the best browser for your main computer and your netbook 🙂

Calling methods in Javascript, without really calling them

Update: I think some people take this a bit too seriously: It’s a fun little experiment: nothing more, nothing less.

Sometimes you’re just lazy. Especially when it comes to typing. And while the round brackets in a function call may not seem like a whole lot of overhead, they do get tiresome if you have to type them over and over again… especially if you don’t think you need them since the function doesn’t return anything and needs no arguments: Something that’s awfully common in object-oriented UI programming.

Surprisingly enough, this isn’t all that difficult to do in Javascript, since a lot of methods are called implicitly… toString is probably the most famous one, but there’s also valueOf that does more or less the same but is called for numeric (and some other) casts.

The simplest way to call it is including a sign:

+myFunction;

which effectively translates to

window.parseFloat(myFunction.valueOf());

so all we need to do is provide a valueOf method that calls the function itself, like so:

Function.prototype.valueOf=function(){this.call(this); return 0;};

and suddenly the plus sing is all that’s needed for our call.

Especially in an object oriented environment you’ll have a lot of these calls, but you’ll have to fix the scope since these methods would be called in the scope of the method itself:

Function.prototype.fix=function(s){var t=this; return function(){ return t.apply(s,arguments); }; };

Using this method in the constructor to overwrite each method with a fixed-scope wrapper solves this:

var Foo=function(){
  this.myMethod=this.myMethod.fix(this);
};

or a bit more automated:

var Foo=function(){
  for(var i in this)
    if(typeof(this[i])=="function")
      this[i]=this[i].fix(this);
};

and finally we end up with this whole example (after a bit of OOP refactoring):

var StandardClass=function(){};
  StandardClass.prototype.initMethods=function(){
    for(var i in this)
      if(typeof(this[i])=="function" && this[i].dontWrap!==true)
        this[i]=this[i].fix(this);
};
StandardClass.prototype.initMethods.dontWrap=true;

Function.prototype.fix=function(s){
  var t=this;
  return function(){
    return t.apply(s,arguments);
  };
};

Function.prototype.valueOf=function(){
  this.call(this);
  return 0;
};

var Foo=function(name){
  this.initMethods();
  this.name=name;
};
Foo.prototype=new StandardClass;

Foo.prototype.showName=function(){
  alert(this.name);
};

Foo.prototype.showNameUpperCase=function(){
  alert(this.name.toUpperCase());
};

var myFoo=new Foo("Hello World");

+myFoo.showName;
+myFoo.showNameUpperCase;

Why it is right for null to be of type object in Javascript

I’m really amazed how many articles you can find about how stupid it is that typeof null returns object in Javascript. Many people feel that this is wrong since null basically means “not currently an object”.

The mistake here is thinking that a variable with type object actually holds an object. It’s a simple mistake to make, but one that will bite you times and times again:

A variable of type object actually means object-pointer. Unlike primitive types which have more less a direct value, these variables don’t actually hold a value itself, just a non-exclusive pointer to an object. That pointer is their value.

That’s also why objects are apparently passed by reference to functions: While they are actually passed by value, the passed value is the pointer.

If you look at it like this, it actually seems kind of bizarre that typeof null could return anything but object. After all it is still a pointer, just a pointer that points nowhere.

HTML Tutorial (in German)

It’s not finished yet, but I’m writing this for a friend to help her with her classes and it might already be useful for others too:

I couldn’t find what I consider a good tutorial on HTML (meaning that it focuses on document structure instead of flashy design), so I started writing my own.

In its current state as it covers HTML, or more precisely XHTML (HTML has too many implicit rules to be an effective learning tool in my oppinion) and everything needed (Unicode, XML, tools, …). However CSS and Javascript are not yet done.

http://www.tapper-ware.net/stable/HTML.Tutorial/index.xhtml

Emulating SVG path animated d attribute with Canvas

This isn’t particularly breathtaking, but I was looking at creating a simple animation without Flash. And seeing as I’m most comfortable with Inkscape as my primary vector graphics editor I figured “Why not just animate the path’s data attribute to interpolate keyframes?”

Sadly, I couldn’t find any browser that supports it yet, but I wasn’t ready to give up my hope of using Inkscape to generate the data… so I looked into using Javascript to animate everything. I eventually moved from using the SVG Dom to Canvas based drawing, but the data comes straight from a SVG document:

http://www.tapper-ware.net/stable/HTML5-animate-path-d/testdata.svg

This isn’t really exciting or breathtaking, just a friendly reminder what we could do if the path d attribute was finally animated 🙂 .

http://www.tapper-ware.net/stable/HTML5-animate-path-d/