Javascript storing/state of global data/object

爷,独闯天下 提交于 2020-01-01 16:53:29

问题


Is there a way to store global data in the window object such that the data can survive page reloads/refresh. So lets say I assign my global data/object -

window.myObject = myProductObject

And the user refreshes/reloads the page or may be jumps to another page of my website. Is window.myObject still available after the page reload?

NOTE -: I cannot store the object in a cookie, since its a object, I mean it could be a reference to another custom object or it could refer to another "window" object which has opened via "window.open"


回答1:


Use the window.top.name hack

var data = window.top.name ? JSON.parse(window.top.name) : {}
...
window.top.name = JSON.stringify(data)

window.top.name persists across page loads

I recommend you use an abstraction like lawnchair instead though




回答2:


You CAN save objects in cookies. But localStorage is better. Is similar to a cookie but you get 5Mb to use.

You have to JSON encode/decode if you save objects instead of strings, but that is easy with a wrapper on localStorage or cookie.

Here is a really simple wrapper for localStorage (you have 5Mb to use):

var Storage = {
    set: function(key, value) {
        localStorage[key] = JSON.stringify(value);
    },
    get: function(key) {
        return localStorage[key] ? JSON.parse(localStorage[key]) : null;
    }
};

And you can use it like this:

$(function() {
    var defaultValue = {param1: 'value',counter: 0 },
        myObj = Storage.get('myObj') || defaultValue; // get the obj from storage or create it with default values

    $('body').html('counter: ' + myObj.counter);
    myObj.counter+=1; // increment counter 
    Storage.set('myObj', myObj); // save it to localStorage
});
​

You can try it on this jsFiddle: http://jsfiddle.net/guumaster/LytzA/3/




回答3:


You could try storing a string representation of your object in a cookie, provided the object is made up of values only (no methods), eg

var foo = { a: "a", b: "b" };
document.cookie = "foo=" + JSON.stringify(foo);

There's a good cookie reader / writer example here - https://developer.mozilla.org/en/DOM/document.cookie




回答4:


I'm not sure how this fairs cross-browser. I at least got it to work in chrome, firefox and IE9 and IE8/7 in compatibility mode, but you will get warned about popups. You can detect if popups are being blocked and refuse to load anything until they are enabled for your site. See Detect blocked popup in Chrome

I'm using jQuery to bind to the beforeunload event, you can use your preferred solution.

jQuery(function ($) {
    $(window).bind('beforeunload', function () {
        window.open("", "_savedata", "titlebar=0,width=100,height=100").saveData = window.saveData;
    });

    var store = window.open("", "_savedata");      
    window.saveData = store.saveData;
    store.close();    
});

Example: (refresh the page a few times)

http://jsfiddle.net/hZVss/1/

And as requested by @Raynos - persisting closure state - something you can't serialise (works in firefox and chrome at least, IE calls it a security issue, but might be something to do with how jsfiddle is using frames)

http://jsfiddle.net/ght9f/2/

Disclaimer: I wouldn't vouch for the elegance of this solution. I was merely curious about persisting object state using popups. Serialising your object to JSON and storing it in a client side store is much better (@Raynos would recommend lawnchair https://github.com/brianleroux/lawnchair/). You should avoid cookies if you can as this data gets posted back to the server, which might not be ideal.

If your main objective was to persist references to popup windows you can actually do this by giving the popup a name. This is exactly how I am persisting my reference to the popup that I create on refresh.



来源:https://stackoverflow.com/questions/9652070/javascript-storing-state-of-global-data-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!