JavaScript: Detecting and using localStorage

Hi,

I've been playing with localStorage to transfer data between browsers

How do I detect if localStorage is enabled and if the storage object I'm trying to use has been set?

Note: Code untested
<html>
<head>
  	
<script type='text/javascript'>

  function SetLocal(FooBar){
localStorage.getItem('MyObj', FooBar);
document.getElementById('ret').html = "set " + FooBar;

}
function GetLocal(){
  if(!windwow.localStorage   )  { //|| !localStorage.getItem('MyObj')
      document.getElementById('ret').html = "localStorage Not set";
      // Do back up code
    }
  else{
   // use localStorage 
   var res = localStorage.getItem('MyObj');
    document.getElementById('ret').html = res;
  }
}
 
</script>


</head>
<body>
<div>
<button onclick="SetLocal(Foo)">Set Foo</button>
<button onclick="SetLocal(Bar)">Set Bar</button>
<button onclick="GetLocal()">Get Local</button>

</div>
<div id="ret">

</div>

</body>
</html> 

Open in new window



Also I'm assuming that as the localStorage  object is named  it will be overwritten   is there a away to make it unique?

Fianly is localStorage cleared on browser exit if "Delete browsing history on exit" is set
LVL 1
trevor1940Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lenamtlCommented:
You can use modernizr https://modernizr.com/

https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js

the way to detect it
<script type="text/javascript">
if (Modernizr.localstorage == false) {
// your code here												
}
else { 
// your code here										
}
</script>

Open in new window


you can setItem and getItem
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
// Save data to the current local store
localStorage.setItem("username", "John");

// Access some stored data
alert( "username = " + localStorage.getItem("username"));

Open in new window


For object
var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Set the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Open in new window

0
trevor1940Author Commented:
You can use modernizr https://modernizr.com/

Due to system restrictions links to external libraries or scripts are blocked
I can have JavaScript within the webpage only
0
ste5anSenior DeveloperCommented:
Then deliver the library from your server.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

lenamtlCommented:
modernizr is just for the detection

(if (Storage !== void(0))
  {
  // localStorage and sessionStorage support!

  }
else
  {
  //  No support..
  }

Open in new window

or
if(window.localStorage!==undefined){
    //yes
}else{
   //no
}

Open in new window



You don't need modernizr to setItem and getItem
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Just found this on stackoverflow presumably I can do both at once?

but then   is that over kill?

if(window.localStorage!==undefined  || localStorage.getItem('testObject') !== null ){
    //yes
}else{
   //no
}

Open in new window

0
lenamtlCommented:
It is always depend what you want to do.

Let say you can have a check to verify if the localstorage is enable to warn user to update their browser or enable the feature..
I usually put this on login page for debugging purpose.

You can have another case to check if the value is set as maybe the browser history get cleared and the value is no more there so in this case do something like set the value if not set yet...

There other case that you may want to remove a  localstorage item
localStorage.removeItem("phone");

Open in new window


Take a moment to read some info https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
0
trevor1940Author Commented:
Thanx for your help and advice
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.