1

My JavaScript code stores its state in a small key-value dictionary:

var my_state = { foo: "bar", baz: "quo" }; // It is a bit longer than that. :-)

I want to store this state in the URL to the page:

http://example.com/page.html#state=eyBmb286ICJiYXIiLCBiYXo6ICJxdW8iIH0K

I want that state to be compressed, so an URL would be shorter.

How do I do that?

Preferably, the compression code would be aware that it is compressing for an URL component, and will choose the alphabet so the result would not have to be encoded. (No further awareness of history API is required — there is Director for that.)

Alexander Gladysh
  • 39,865
  • 32
  • 103
  • 160

1 Answers1

0

What about encoding with stringify and base64?

var my_state = { foo: "bar", baz: "quo" };
var s1 = JSON.stringify(my_state);
var s2 = btoa(s1);
console.log(s2);
// result: eyJmb28iOiJiYXIiLCJiYXoiOiJxdW8ifQ==

But the btoa method is only available in Chrome/Mozilla, have a look at this question to find a cross-browser base64 library: How can you encode a string to Base64 in JavaScript?

Community
  • 1
  • 1
Marc
  • 6,749
  • 9
  • 47
  • 78
  • Well, yes, but this method does not compress data — an base64 still should be encoded... – Alexander Gladysh Sep 12 '13 at 09:10
  • My current plan is to use https://github.com/floydpink/lzwCompress.js in conjunction with https://stringencoders.googlecode.com/svn/trunk/javascript/base64.js, but that is suboptimal. I'd prefer a patched version of lzwCompress that would save directly in the format I need. – Alexander Gladysh Sep 12 '13 at 09:17
  • http://pieroxy.net/blog/pages/lz-string/index.html is much better than lzwCompress. But still looking for an URL-aware solution. – Alexander Gladysh Sep 12 '13 at 11:02
  • NB: Base64 has an URL-safe alphabet (see http://www.rfc-editor.org/rfc/rfc4648.txt( – Alexander Gladysh May 13 '15 at 15:49