1

How can I keep javascript objects alive in a multi-page app (browser independently)?

I know I can for example write a Chrome extension with a background page that would solve it, but is there a browser independent way for this?

2
  • What do you mean by "multi-page"? Multiple frames/windows? Commented Apr 26, 2012 at 12:35
  • multiple pages, at least, that's how I initially designed the UI. Commented Apr 26, 2012 at 12:50

3 Answers 3

2

One approach is to have your javascript code load the pages (via 'ajax' calls) and then replace the body of the html, or parts of it. This way, as far as the browser is concerned you're still on the same "page". You'll have to make sure all the links within your website are void and instead of causing a browser page load, they actually trigger a javascript function. This is the way Facebook, for example, manages clicks on its website. See https://stackoverflow.com/a/7425870/562906

Sign up to request clarification or add additional context in comments.

3 Comments

Compared to the localStorage approach, this way you don't have to explicitly save data (or decide what you need to save). Also, it's compatible with a lot more browsers.
fair enough however everything is now AJAX calls correct? so some complexity is added there also 'compatible with more browsers' - he asked the question with html5 being assumed
wal, you can implement this by writing a single handler that replaces all the links on your site and adds handlers to all of them so you don't have to manually manage this complexity, aside for the one-time overhead. I think that's what Facebook does, by the way.
1

As you are using html5 you could use local storage to store JSON representations of your objects:

var json_text = JSON.stringify(your_object, null, 2);

localStorage.setItem("someKey", json_text);

and then to retrieve your item when on the other page:

var your_object = JSON.parse(localStorage.getItem("someKey"));

To use JSON.stringify you may need JSON-js - if the browser does html5 it appears likely that you won't need the third party script.

2 Comments

JSON is included in most browsers. He should not need to download JSON-js.
Here is the link for you en.wikipedia.org/wiki/….
0

You can use cookies to pass data between page requests. Apart from that, you always have to reconstruct your objects from the beginning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.