Reputation: 7456
I have Javascript on a page that sets localStorage data:
localStorage.setItem('blah', 1);
Then, I have code that will redirect to another page on a button click.
On the other page I try to access the item in localStorage, but I get Uncaught TypeError: Cannot read property 'blah' of null
30% of the time. How come localStorage isn't saving each time?
Am I missing something?
On Current Page
localStorage.setItem('blah', 1);
$('.btn').on('click', function() { window.location.href = 'http://example.com/signup?redirect=/chkout'; });
On Redirect Page
localStorage.getItem('blah', 1); ==> null
Upvotes: 4
Views: 5172
Reputation: 7634
This might happen because
The user agent may throw a SecurityError exception and abort these steps instead of returning a Storage object if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to persist data).
If the Document's origin is not a scheme/host/port tuple, then throw a SecurityError exception and abort these steps.
Upvotes: 1
Reputation: 1360
The localStorage data should persist, by several documentations. There may be a case when your localStorage data gets overwritten by some other operation. You can try to debug this by adding following eventListener:
window.addEventListener("storage", function(data) {
console.debug(data);
}, false);
This should log the data, every time the storage is accessed.
Upvotes: 0