Skip to content

Instantly share code, notes, and snippets.

@sagar-ganatra
Created October 10, 2012 10:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sagar-ganatra/3864629 to your computer and use it in GitHub Desktop.
Save sagar-ganatra/3864629 to your computer and use it in GitHub Desktop.
Local storage event listeners
<!DOCTYPE html>
<html>
<head>
<title>localStorage Test</title>
<script type="text/javascript" >
var count = 0;
var storageHandler = function () {
alert('storage event 1');
};
window.addEventListener("storage", storageHandler, false);
</script>
</head>
<body>
In Page 1
<button id="addBtn"
onclick="localStorage.setItem('key1',count++)">
Add
</button>
<button id="clearBtn"
onclick="localStorage.clear()">
Clear
</button>
</body>
</html>
@VikashSaharan1
Copy link

this is not working on Chrome & Firefox both.

@subversivo58
Copy link

subversivo58 commented Oct 7, 2018

Hi @VikashSaharan1

This works between two or more windows in the same origin ... the logic applied here is that: other windows that are not in focus receive an event stating that there has been a change in storage.

The assumption is that the page in focus will already know all the interactions with the localStorage ... foolish guess, but that's what happens.

The only bad point of this example is to use alert(), this blocks the storage until pop-up is terminated.

But it's still a good example.


PS:

A bit offtopic, usually this feature is used to do "an ugly thing" a shim for browsers that do not support BroadcastChannel API ... I saw numerous polyfills for this API using this localStorage event

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment