Ugly Variables and Encapsulation

Ugly Variables
The variables within a bookmarklet are scoped to the current page. This means that the variables are treated as if they were coming from whichever page you are looking at when you trigger the bookmarklet.

In order to minimize that risk that a bookmarklet variable will collide with a variable already on the page (that is, will overwrite or reset a global variable that was set by the page author), it's wise to use variable names that are "ugly". The ugly variable is a a random string of upper- and lowercase letters and numbers. (e.g. - c39Yt2U). There are 62 symbols that can be used in such a string.

You can calculate the probability of collision between two randomly chosen ugly variables of the same length (a lower probability meaning a safer bookmarklet). If only one ugly variable is used then the probability is just 1 divided by the number of possibilities - as given in the table below.

Length of variable Formula Number of possibilities
1 62 62
2 62 x 62 3844
3 62 x 62 x 62 238,328
4 62 x 62 x 62 x 62 14,776,336
5 62 x 62 x 62 x 62 x 62 916,132,832
6 62 x 62 x 62 x 62 x 62 x 62 56,800,235,584

We see that ugly variables of length 6 and above are extremely unlikely to collide with such a variable on another page; there are fewer than 1,000,000,000 pages currently on the web (according to some estimates for 1999.)

I thank Ulrik Gade for his help with this idea.

You can sometimes encapsulate the script of a bookmarklet within a function and thereby reduce the number of global variables used to one.

To do this for the 4.0 browsers, wrap a function around the script. That is,
  • Change javascript:
  • to javascript:VARIABLE={x : function(){
  • Localize internal variables (e.g. - put var y, for each variable y.)
  • End the bookmarklet with }};VARIABLE.x()
  • Replace VARIABLE with an ugly variable.
This leaves you with only one ugly variable. The variables inside the script, and the function x(), are scoped to the object named by the ugly variable, so you can replace the variables inside the script with variables of length 1.

For example, here is one way to write a bookmarklet which asks for some text and then alerts it back:
javascript:V1=prompt('First name...','');V2=prompt('Last name...','');alert(V1 + V2)
try it.

As it stands, this bookmarklet is using two (ugly) variables (V1 and V2). We can reduce the number of variables to one by rewriting the script in the following way:
javascript:V1={x:function(){var A=prompt('First name...','');var B=prompt('Last name...','');alert(A + ' ' + B)}};V1.x()
try it

The variables A and B are scoped to the function x(), and x() is scoped to the ugly object V1.

If you are using many small variables in a bookmarklet you may be able to improve it by encapsulating it this way.


Back to Javascript for Bookmarklets