4

The following code

  $(document).ready(function(){

    sessionStorage.test = false;  

    alert( sessionStorage.test );

    if ( sessionStorage.test ) {
      alert("I dont care about your conditions!");
    }

  });

produces the following popups:

false

I dont care about your conditions!

even though sessionStorage.test is clearly set to false. Why is that the case? According to this answer https://stackoverflow.com/a/17986241/2311074, this should work. What am I doing wrong? I am using XAMPP - does it maybe have problems with sessionStorage? Here is the complete code of my test file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script >
      $(document).ready(function(){
        sessionStorage.test = false;    
        if ( sessionStorage.test ) {
          alert("I dont care about your conditions!");
        }
      });
    </script>
  </head>
  <body>
    <!-- page content -->
  </body>
</html>
Community
  • 1
  • 1
Adam
  • 25,960
  • 22
  • 158
  • 247
  • What do you mean by "it returns"? Javascript code with an `alert()` function call does not "return" anything. – arkascha Aug 24 '16 at 15:47
  • Mmm, I'd look on the console and have a look there might be an error, also sessionStorage is a local storage thing for the browser. I'm not sure you can just set an extra variable like that – Richard Housham Aug 24 '16 at 15:48
  • @arkascha your right, bad phrasing. I change it. I mean I get 2 popups. – Adam Aug 24 '16 at 15:49
  • The Storage API only stores strings and a non-empty string is truthy – Andreas Aug 24 '16 at 15:49
  • @Andreas so the accepted answer from my linked question is wrong, has 10 votes and no-one checked? – Adam Aug 24 '16 at 15:50
  • Yes. The [specification](https://html.spec.whatwg.org/multipage/webstorage.html#storage-2) clearly says that `.setItem()` expects a `DOMString` as the value parameter and `.getItem()` returns a `DOMString` – Andreas Aug 24 '16 at 15:57

1 Answers1

7

The default getter/setter for sessionsStorage are:

sessionStorage.setItem('keyName', 'value');    
sessionStorage.getItem('keyName')

So, for example:

sessionStorage.setItem('test',false);    
if (sessionStorage.getItem('test') != "false") {
   ..........
}

Duplicate Topics:
- sessionStorage setItem returns true or false
- sessionStorage isn't working as expected

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • Okay.. So I have to do something like `if( sessionStorage.getItem('test') == "false")`? Thank you! I accept answer as soon as timer is expired. – Adam Aug 24 '16 at 15:54
  • i have updated answer, yes, you should `... != "false"` – T.Todua Aug 24 '16 at 15:55