Driss Zouak
Driss Zouak

Reputation: 2401

SessionStorage seems to remain empty

I'm new to HTML5/Javascript and am having a conceptual issue I think. I'm using Aptana as my environment and it is using FireFox for the browser to debug.

Here's the code in question:

var req = new ContactRequest("Mister Peachy", "peach.png", "One Liner Message" );

sessionStorage.Requests = new Array();
sessionStorage.Requests[0] = req;

req = new ContactRequest("Anon Ymous", "person.png", "Another one line msg");

sessionStorage.Requests[1] = req;

The issue seems to be that sessionStorage.Requests always equals "" . I tried using .setItem but that didn't work either.

Upvotes: 0

Views: 3639

Answers (3)

sciritai
sciritai

Reputation: 3758

What you need to do is stringify your data to store and parse it to retrieve. Here's a little interface that I have written

App.session = (function () {
  var self = {};

  self.get = function (key) {
    var b = sessionStorage.getItem(key);
    return b ? JSON.parse(b) : null;
  }

  self.set = function (key, value) {
    var b = JSON.stringify(value);
    sessionStorage.setItem(key, b);
  }

  return self;
})();

var session = App.session;
session.set('foo', 'bar');
var bar = session.get('foo');
console.log(bar);

Upvotes: 2

Dennis
Dennis

Reputation: 32608

From the documentation,

Each Storage object provides access to a list of key/value pairs, which are sometimes called items. Keys are strings. Any string (including the empty string) is a valid key. Values are similarly strings.

Emphasis added. You can't store objects in sessionStorage.

Mozilla also has comments on this:

Note: Although the values can be set and read via the standard JavaScript property access method usage of getItem and setItem methods is recommended.

Note: Keep in mind that everything you store in any of the storages described in this page is converted to string via its .toString method before stored. So trying to store a common object will result in string "[object Object]" to be stored instead of the object or its JSON representation. Using native JSON parsing and serialization methods provided by the browser is a good and common way for storing objects in string format.

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 220126

sessionStorage cannot store objects, it can only store strings.

If you want to store anything else, you'll have to use JSON.

Upvotes: 1

Related Questions