-1

On my webpage I have a status object that stores a few values.

var status = { animal: "cat", page: 4};

I would like to be able to update the URL with a unique ID that represents that state of the status object.

http://my.website#/searchPage/472940283648

The javascript on the page would need to read in the number, and from it produce a status object.

I suppose I could save the status object in a database, but is there a way to convert the object into a reversable hash of some sort?

BishopZ
  • 6,269
  • 8
  • 45
  • 58

1 Answers1

2

You can use the btoa function to encode a string with base64 scheme. And atob to decode it back.

var obj = { animal: "cat", page: 4 };

// Encode to base64
var hash = btoa(JSON.stringify(obj));

// Decode back to object
var decodedObj = JSON.parse(atob(hash));

If you want to put it in URL, don't forget to use encodeURIComponent first, since base64 may contain a character like: =, +, /.

var hashPart = encodeURIComponent(btoa(JSON.stringify(obj)));
var url = 'http://my.website#/searchPage/' + hashPart;

// Decode the uri first
var decodedObj = JSON.parse(atob(decodeURIComponent(hashPart)));

Also, note that the status variable is part of the global variables on some browsers.

Risan Bagja Pradana
  • 4,494
  • 1
  • 20
  • 22