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"