Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom localStorage js function not running in Chrome

What I'm trying to do:

Create my own storage API on top of localStorage so it is easier to use in my own code.

Why?

So it has an API for my purposes and can be extended later.

System:

Chrome Version: Version 22.0.1229.94 m

JSFiddle: http://jsfiddle.net/ttback/kr88W/

Error

The fiddle will trigger an error in Console:

TypeError: Property 'localStorageSave' of object # is not a function

This works in IE 8 and Firefox 16.0.1, so I am wondering if I'm missing something or is it a Chrome bug.

Code:

<html>
<head>
<title>JS function not working in Chrome</title>
<script type="text/javascript">
var localStorage = localStorage || {};
localStorage.localStorageSave = function(){
    alert("SAVE");
};
localStorage.localStorageSave();
</script>
</head>
<body>

    
</body>

</html>​
like image 752
ttback Avatar asked Oct 16 '12 18:10

ttback


People also ask

How do I access localStorage in JavaScript?

You can access the localStorage functionality through the Window. localStorage property. This property provides several methods like setItem(), getItem(), and removeItem(). You can use these to store, read, and delete key/value pairs.

How do I know if my browser supports localStorage?

localStorage browser support To be sure the browser supports localStorage , you can check using the following snippet: if (typeof(Storage) !== "undefined") { // Code for localStorage } else { // No web storage Support. }


1 Answers

When you do

localStorage.localStorageSave = function(){
    alert("SAVE");
};

you're doing the same as

localStorage["localStorageSave"] = function(){
    alert("SAVE");
};

or

localStorage.setItem("localStorageSave", (function(){
    alert("SAVE");
}).toString());

You're in fact not saving a function in localStorage, because localStorage saves only strings.

You can check it with

console.log(typeof(localStorage.localStorageSave));

You get "string". This isn't a function and is normal.

like image 130
Denys Séguret Avatar answered Oct 26 '22 03:10

Denys Séguret