Created
October 10, 2012 10:28
-
-
Save sagar-ganatra/3864629 to your computer and use it in GitHub Desktop.
Local storage event listeners
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 supportBroadcastChannel
API ... I saw numerous polyfills for this API using thislocalStorage
event