'window.onstorage event doesn't seem to trigger

I'm working on a workaround with a synch'ing parent window, child window and grandchild window. I want to refresh the parent from the grandchild in case the child window is closed and the opener chain is broken. I figured on setting a localStorage variable, my_variable, in the grandchild (when it's opener, child, is closed) and putting the following in the parent onload...

window.onstorage = function(e) {
     if (e.key==="my_variable")
        refreshMe();
     }
}

I've verified my_variable value by adding localStroage.getItem("my_variable") to a button on the parent. So even when child is closed, the localStorage value does get to the parent. So I think the problem is with capturing the onstorage event. But it seems so straightforward and the parent onload executes to completion, i.e. the above throws no error. i should add this is legacy IE11 rendering as IE 9, but everything I've read said that code should work. Thank you very much.



Solution 1:[1]

window.onstorage is triggered when localStorage is updated from a different document on the same domain.

Quotting from the MDN reference for onstorage:

"...won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made"

See: https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

You'll have to find another mechanism to check changes to local storage on the document where the changes are made.

Solution 2:[2]

What worked for me is to change the value in the triggering code:

<button onclick="triggerLS();">refresh other pages</button>

<script>
localStorage.setItem("my_variable","0"); // set initial value
function triggerLS(){
    v=1-localStorage.getItem("my_variable"); // toggle value between 1 & 0
    localStorage.setItem("my_variable",v);
}
</script>

the triggering code being:

window.onstorage = function(e) {
    console.log(e.key, e.oldValue, e.newValue);
    if (e.key==="my_variable"){
         refreshMe();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave Pritlove
Solution 2