Juan John Mathews
Juan John Mathews

Reputation: 736

Localstorage not working as intended in firefox. Returns object of null

I was porting a chrome extension to firefox. Everything is fine in chrome but the following code generates error in firefox.

localStorage.setItem("display_tooltip", false);

data = localStorage.getItem('display_tooltip');
    if(data.display_tooltip)                  //line where error occurs
        display_tooltip = true;
    else
        display_tooltip = false;

I get an error on firefox saying data is null. Where am I doing it wrong. The same code works perfectly when I run the chrome extension. I am using firefox addon-sdk.

Upvotes: 1

Views: 868

Answers (3)

Mavlarn
Mavlarn

Reputation: 3883

you data is:

data = localStorage.getItem('display_tooltip')

Why you using data. display_tooltip to check? Justif (data) { ... } . Maybe you need to check the type of data. Maybe it is string of true or false, but not bool.

Upvotes: 0

ianaya89
ianaya89

Reputation: 4233

It will not work in any browser.

You are setting 'false' to the var data so data.display_tooltip does not exists.

Just ask for the value of data:

if (data == 'true')
  display_tooltip = true;
else
 display_tooltip = false;

Note that localStorage does not store booleans so you need to ask for the 'true' string when you check the value.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

localStorage stores strings not booleans, hence you'll have to compare accordingly. And you need to check for data variable instead of data.display_tooltip, as:

localStorage.setItem("display_tooltip", false);
data = localStorage.getItem('display_tooltip'); 
// variavle 'data' holds value stored in 'display_tooltip' variable
if(data == "true") {
    //your code
    alert("True");
}
else {
    //false, your code
    alert("False");
}

Demo:: jsFiddle

Upvotes: 3

Related Questions