最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - forcing local storage events to fire in the same window - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Aug 6, 2013 at 21:08 Troy CosentinoTroy Cosentino 4,77810 gold badges40 silver badges61 bronze badges 13
  • Some already did. For the others, $(window).trigger("storage") (or the native equivalent) should do it. – Bergi Commented Aug 6, 2013 at 21:33
  • hmm I thought I tried that first and it didn't work. I will give it a try again shorty, thank you – Troy Cosentino Commented Aug 6, 2013 at 22:05
  • @Bergi that works nicely, thank you. How would I include the correctly formatted event object? – Troy Cosentino Commented Aug 6, 2013 at 22:22
  • I tried: $(window).trigger('storage', {}, {originalEvent: {key: 'selectedAdmins'}}); – Troy Cosentino Commented Aug 6, 2013 at 22:23
  • 2 You have yourself put them as the .originalEvent :-) See jsfiddle.net/78e7puhn/2 – Bergi Commented Aug 29, 2014 at 13:47
 |  Show 8 more comments

5 Answers 5

Reset to default 4

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.

Patch the localStorage.setItem function to manually generate a "storage" event within the same window:

const origSetItem = window.localStorage.setItem;

window.localStorage.setItem = function setItem(key, value) {
  // Retrieve old value before we store the new one
  let oldValue = window.localStorage.getItem(key);

  // Store in LocalStorage
  const result = origSetItem.apply(this, arguments);

  // Manually fire a "storage" event so this window is alerted. On its own, 
  // localStorage.setItem() only fires a "storage" event for other tabs.
  const e = new StorageEvent('storage', {
    storageArea: window.localStorage,
    key,
    oldValue,
    newValue: value,
    url: window.location.href,
  });
  window.dispatchEvent(e);

  return result;
}

Now anytime localStorage.setItem() is called, the window's "storage" event will fire.

Whenever you want to trigger it on the same tab, add this line

window.dispatchEvent(new Event("storage"));

Add an event listener for the page

window.addEventListener('storage', storageEventHandler, false);

function storageEventHandler(e) {
    console.log("Hello!")
}

That's all

Yes, you can generate unique id for each tab and compare them, look how this guy did here Another solution I found based on the same idea, generate and compare unique ids.. here

This is easily handled with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String. Of course, it also fires events in the same window/tab for key value changes, such as those made by the set or remove methods.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Once you instantiate the utility, the following snippet will allow you to monitor the events:

function nowICanSeeLocalStorageChangeEvents( e ) {
    console.log(
        "subscriber: "    + e.currentTarget.nodeName + "\n" +
        "timestamp: "     + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
        "prefix: "        + e.detail.prefix  + "\n" +
        "message: "       + e.detail.message + "\n" +
        "method: "        + e.detail.method  + "\n" +
        "key: "           + e.detail.key     + "\n" +
        "old value: "     + e.detail.oldval  + "\n" +
        "new value: "     + e.detail.newval  + "\n" +
        "old data type: " + e.detail.oldtype + "\n" +
        "new data type: " + e.detail.newtype
    );
};
document.addEventListener(
    "localDataStorage"
    , nowICanSeeLocalStorageChangeEvents
    , false
);
发布评论

评论列表(0)

  1. 暂无评论