sessionStorage isn't working as expected

前端 未结 2 1376
有刺的猬
有刺的猬 2021-01-23 07:11

Here is my code:

    sessionStorage.loggedIn = true;

    if (sessionStorage.loggedIn) {
        alert(\'true\');
    }
    else {
        alert(\'false\');
            


        
2条回答
  •  清酒与你
    2021-01-23 08:00

    Try to change your code to

    sessionStorage.setItem('loggedIn',JSON.stringify(true));
    
    if (JSON.parse(sessionStorage.getItem('loggedIn'))) {
        alert('true');
    }
    else {
        alert('false');
    }
    

    and it should work consistently across all major browsers.

    The interface with the setItem/getItem methods is how the spec is written, so going that way is safer than using the shortcut of assigning properties. Also, sessionStorage, like localStorage is a textbased storage mechanism, and not meant for storing objects, so you need to wrap calls with JSON.parse and JSON.stringify to get the expected results across the board.

    Be aware that JSON.parse doesn't always play nice with undefined/null values, so it might be wise to do some type checking first.

    You can read the spec for the storage interface here

提交回复
热议问题