Search code examples
javascriptsession-storage

Javascript storing information across pages


I've been trying to save javascript variables across pages with sessionStorage.

As I understand, the syntax is:

sessionStorage.setItem('whateverkey', 'whatever value');

Is there a way to save a variable inside sessionStorage, or other easy ways to save information across pages

Thanks in advance!


Solution

  • My value is 'null' when I try to access it from another page.

    This is exactly how sessionStorage is designed to work:

    The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

    If you want your data to persist across pages on the same origin, use localStorage instead.