← Previous
Next →

URI-Escaping JavaScript Bookmarklets in Chrome

John Tantalo
03 Oct 2011

John Gruber published a helpful JavaScript Bookmarklet Builder which I used to generate my IPA TTS bookmarklet.

A few users reported that Chrome choked on the bookmarklet. I found that the bookmarklet builder does not produce the output that Chrome expects. I was using Chrome 15.0.874.54 beta.

For example, take this simple script.

(function () {
  // what is 1+1?

Gruber's script produces this bookmarklet:


If you drag this example to your bookmark bar in Chrome, it will produce this error when invoked.

> Uncaught SyntaxError: Unexpected token %

What happened? If you edit the bookmark, you will see that Chrome double-escaped the string,


I believe this happened because the string contained some non-escaped characters such as parentheses.

Gruber points out in a footnote that his script intentionally leaves some characters unescaped for the purpose of readability.

It’s unclear to me what characters must be escaped in a bookmarklet URL. Some sources suggest that other punctuation characters, such as brackets and semicolons, ought to be escaped, too, but I can see no practical reason to do so. If you want to be really conservative and escape just about everything, change this line:

uri_escape_utf8($bookmarklet, qq('" \x00-\x1f\x7f-\xff));



Personally, I prefer to keep the bookmarklet URL itself as readable as possible.

With this change, we get this bookmarklet:


It may not be as readable as "Example 1", but it works.

Find my modifications to Gruber's JavaScript Bookmarklet Builder on GitHub.