0

I made a website which uses localStorage, but I mainly tested it in Opera.

The way the website gets the locally stored data is by using a JS for loop:

for (var key in localStorage) { // DO STUFF! }

When my friends used the website with chrome and firefox they told me it displays random strings.

Screens here: https://i.stack.imgur.com/okfld.png (list on the left are the localstorage keys) and https://i.stack.imgur.com/0Qz5C.png

My first assumption is that Chrome or Firefox added some localStorage items on each visit to the website (deleting the cookies doesn't fix the issue as they re-occur).

The problem is that when my website calls for the users/localStorage, it just says "get all cookie keys" and seems to get literally ALL, even the ones that the browsers create.

I can only think of 1 way to fix it, by just blocking all the keywords that chrome and firefox create within the JS itself, and forcing it not to be shown.

Any ideas? I know this is extremely specific but it is troublesome. additional info, I already checked the extensions they were using, but they don't seem to be the trouble (because I have the same one's and these localstorage anomalies aren't an issue).

Thanks to all responses and putting up with me :)

Also, my website if anyone else wishes to report more bugs:

http://youtube-collections.tumblr.com/

3 Answers3

1

As Mathieu pointed out, localStorage is an object. To prevent it from happening use this:

for (var key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
        // do stuff with it
    }
}

or use forEach methods from lodash (_.forEach()), jQuery (jQuery.each()) or angular (angular.forEach()).

Simon Wicki
  • 4,029
  • 4
  • 22
  • 25
0

It's because localStorage is an object. When you iterate over an object with the for loop you will get all properties from that object, including its methods.

Mathieu David
  • 4,706
  • 3
  • 18
  • 28
  • As I said, this doesn't happen on Opera, so why does it occur on firefox and chrome? And is there any other fixes? Thank you for the reply by the way :) – Lewis Harris Jun 04 '15 at 22:59
  • I have no clue why it does work on Opera, but it shouldn't ;) @zwacky provided the rest of the answer while I was still looking, so take a look at that :) – Mathieu David Jun 04 '15 at 23:03
0

Use Object.keys (and avoid for-in loops):

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Source

Example

var keys = Object.keys(localStorage);
for(var i = 0, key; key = keys[i]; i++) {
   // use key, ie. getItem(key) ...
} 
Community
  • 1
  • 1
  • This worked. Is there any similar ways to check if the localstorage is from the webpage, and not from, say, a browser extension? Thanks :) – Lewis Harris Jun 05 '15 at 16:27