Question

I have a page which works on my localhost.. when I put t on a remote server, it gave an error. the code which returns the error is

  var $app_list = localStorage.getItem('LsAppList');
  var AppListJson = JSON.parse($app_list);
      AppListJson.push({ 
        "extapp_id": appdetail.get("addAppId"),
        "desc": appdetail.get("addAppName"),
        "device_no": appdetail.get("devicenoValue"),
        "validation_key": appdetail.get("activationkeyValue") 
    });

the console log is

Uncaught TypeError: Cannot read property 'push' of null
addToJson EncigoHome.js:126
n.extend.trigger kendo.mobile.min.js:9
s.extend._release kendo.mobile.min.js:15
i._userEvents.o.UserEvents.tap kendo.mobile.min.js:15
n.extend.trigger kendo.mobile.min.js:9
l.extend.notify kendo.mobile.min.js:13
u.extend._trigger kendo.mobile.min.js:13
u.extend.end kendo.mobile.min.js:13
l.extend._eachTouch kendo.mobile.min.js:13
l.extend._end kendo.mobile.min.js:13
arguments.length.t.(anonymous function) kendo.mobile.min.js:10
b.event.dispatch jquery-1.9.1.js:9593
v.handle
Was it helpful?

Solution

localStorage is per domain (more specifically same origin). The localStorage associated with the remote domain does not have access to the values stored in the localStorage associated with your localhost.

You should check to see if there is a stored value and fallback to a default one or treat the error:

var $app_list = localStorage.getItem('LsAppList');
var AppListJson = $app_list != null ? JSON.parse($app_list) : [];
//...

More verbose:

var $app_list = localStorage.getItem('LsAppList'),
    AppListJson;
if ($app_list != null) {
    AppListJson = JSON.parse($app_list);
} else {
    // treat no LsAppList stored case
    // you could show a message or set it to a default value
    AppListJson = [];
}

This "no previously stored data" scenario will happen whenever the user clears his browser data or switches browsers/devices as well, so it must be treated properly.


The root cause of the error, as you've probably figured out already, is that localStorage.getItem(key) returns null when no value is stored for the given key in the current domain. Then JSON.parse(null) === null and null.push() throws.


Just as a nitpick, I'd suggest reviewing your variables naming:

  • Don't use PascalCase naming for non-constructors.
  • Don't mix camelCase with underline naming conventions.
  • Recommended read: Idiomatic.js naming.

And also, AppListJson is not JSON, it is a native array. JSON can only exist in string context, that is, your $app_list is JSON. More in-depth explanation about JSON/not JSON: There's no such thing as a "JSON Object"

OTHER TIPS

The .push() method can only be used on arrays.

It seems that you don't have the item stored in localStorage, which is why it is returning null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top