Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for Storing JSON in URL Hash / Fragment

I'm building a single-page AJAX application, and would like to under certain circumstances store state in JSON after the URL hash (#). I've seen a couple other sites do this, but I'm hoping to get some best practices, tips, or gotchas as I work to implement this.

like image 507
DuckMaestro Avatar asked Mar 15 '11 23:03

DuckMaestro


1 Answers

I would actually advise against encapsulating data into json and then putting it into the hash. The reason is that JSON itself needs a lot of markup and will actually open some security holes as you'll have to later eval code that comes directly from the user.

As a better alternative, I would advise using x-www-form-urlencoded as encapsulation. For example if this is your state object:

var stateObject = {
  userName: 'John Doe',
  age: 31
}

Then you would create a hash fragment like this:

// Create an array to build the output string.
var hashPartBuffer = [];
for (var k in stateObject) {
  hashPartBuffer.push(
    encodeURIComponent(k),
    '=',
    encodeURIComponent(stateObject[k]),
    '&'); 
}
if (hashPartBuffer.length) {
  // Remove the last element from the string buffer
  // which is '&'.
  hashPartBuffer.pop();
}
var hashPartString = hashPartBuffer.join('');
// This will now be 'userName=John%20Doe&age=31'

Then you will parse this back by:

var hashPartString = 'userName=John%20Doe&age=31';
var pairs = hashPartString.split(/&/);
var stateObject = {};
for (var i = 0; i < pairs.length; i++) {
  var keyValue = pairs.split(/=/);
  // Validate that this has the right structure.
  if (keyValue.length == 2) {
    stateObject[keyValue[0]] = keyValue[1];
  }
}
like image 187
Sorin Mocanu Avatar answered Sep 23 '22 17:09

Sorin Mocanu