I recently discovered two obscure JavaScript functions in Firefox: window.btoa and window.atob which encode and decode Base64 data, respectively. While I can’t think of any practical use for these functions in day-to-day coding (for the client-side, at least), I figured it would be a good exercise for me to implement them in the other browsers — if only for the satisfaction of understanding the Base64 algorithm. Oh, and for nerd street cred.
Download: base64.js
Note that the atob function throws an exception on a malformed Base64 encoded string (as does the native Firefox implementation), so it is a good idea to wrap calls to it in a try/catch block. Otherwise, usage is straightforward:
var original = 'Hello World!';
btoa(original); // SGVsbG8gV29ybGQh
(atob(btoa(original)) == original); // true
btoa('\u0009'); // CQ== (works with low ASCII values also)
For good measure, here is a little test widget: