Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forcing local storage events to fire in the same window

From many sources, I have found that the local storage events only fire in windows/tabs that did not originate the change.

My question is, is there any way I could detect change from the same window? Or perhaps override the functionality to force the event to fire within the same window/tab?

It just seems impractical to not include the option, but I cannot find a way to do it.

Thanks

like image 262
Troy Cosentino Avatar asked Aug 06 '13 21:08

Troy Cosentino


People also ask

Can local storage be manipulated?

localStorage works similarly to sessionStorage , but the difference is that data stored in localStorage is persistent and lasts forever for that specific domain unless the browser's cache is cleared or we clear localStorage using JavaScript because localStorage data can only be manipulated by JavaScript.

What event is fired after web storage update?

A storage event is fired when you insert, update or delete a sessionStorage or localStorage property.

What is storage event in JS?

The storage event of the Window interface fires when a storage area ( localStorage ) has been modified in the context of another document. Note: This 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.


1 Answers

FYI, here is what I ended up with.

localStorage.setItem('selectedOrgs', JSON.stringify(this.selectedOrgs));

// trigger the event manually so that it triggers in the same window
// first create the event
var e = $.Event("storage");

// simulate it being an actual storage event
e.originalEvent = {
    key: 'selectedOrgs',
    oldValue: prev,
    newValue: JSON.stringify(this.selectedOrgs)
};

// Now actually trigger it
$(window).trigger(e);

Note: I only use oldValue and newValue.. if you use other attributes make sure and set them appropriately.

You could also overwrite localStorage.setItem so that it fires in the current window in a similar way.

like image 104
Troy Cosentino Avatar answered Sep 23 '22 15:09

Troy Cosentino