I know how to bind change event to localStorage if the same page opened in two tabs (this topic) and i need the similar effect, but if i had two pages of one site opened in different tabs. Any ideas?
Asked
Active
Viewed 4,108 times
1
-
ping the localstorage on the second page at a time interval – madalinivascu May 09 '16 at 08:43
-
When localStorage is modified, a storage event will be fired on all other pages that share the storage. You just need to handle the event, and retrieve updated data. This also works for sessionStorage. – Yin Gang May 09 '16 at 10:17
-
@YinGang i'm trying to create storage item and the second page sees it but only after refresh. '$(window).bind('storage' ....' isn't working – Nick Kostikov May 09 '16 at 10:37
-
@NickKostikov, I've post an answer, just save them as two html files under your site root, and load both in browser, check is it what you want. Thx. – Yin Gang May 09 '16 at 13:29
2 Answers
1
Make an example for you, check is it what you want?
http://www.yoursite.com/page1.html
<html>
<head>
<title>Page 1</title>
</head>
<body>
<input type="text" id="value"/>
<button id="save">Save</button>
</body>
<script>
function $ID(id){
return document.getElementById(id);
}
function addHandler(ele,trigger,handler){
if(window.addEventListener){
ele.addEventListener(trigger,handler,false);
return false;
}
window.attachEvent(trigger,handler);
}
function saveToStorage(){
var value = $ID('value').value;
window.localStorage.setItem('key',value);
}
addHandler($ID('save'),"click",saveToStorage);
</script>
</html>
http://www.yoursite.com/page2.html
<html>
<head></head>
<body>
value:
<span id="value"></span>
</body>
<script>
function addHandler(ele,trigger,handler){
if(window.addEventListener){
ele.addEventListener(trigger,handler,false);
return false;
}
window.attachEvent(trigger,handler);
}
function onStorageEvent(e) {
var value = localStorage.getItem('key');
console.log('Successfully communicate with other tab');
console.log('Received data: ' + value);
document.getElementById('value').innerText = value;
}
addHandler(window,"storage",onStorageEvent);
</script>
</html>
0
You can use storage event. This is vanilla js.
window.addEventListener('storage', () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('sampleList')));
});
// or
window.onstorage = () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('sampleList')));
};

w411 3
- 2,594
- 2
- 18
- 21