David
David

Reputation: 7456

Data stored in localStorage isn't there when I redirect

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

Answers (2)

try-catch-finally
try-catch-finally

Reputation: 7634

This might happen because

  1. The tab/window is in incognito / private surfing mode
  2. The browser is configured to track no history at all
  3. The item was set on another port or scheme (of the same domain) (e.g. http://foo.com instead of https://foo.com)

From the W3C specification:

  1. 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).

  2. If the Document's origin is not a scheme/host/port tuple, then throw a SecurityError exception and abort these steps.

Upvotes: 1

Ravi
Ravi

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

Related Questions