SoFunction
Updated on 2025-03-09

Summary of implementation methods for real-time monitoring of localStorage changes in JavaScript

Listen to localStorage changes in different windows/tabs

whenlocalStorageWhen the data of  changes in one window/tab, other windows/tabs of the same origin will triggerstorageevent. We can use this event to listenlocalStorageChanges.

Sample code

// Add storage event listener('storage', function(event) {
  if ( === 'groupID') {
    ('New value:', );
  }
});

explain

  • storageEvents will be fired in other windows/tabs of the same origin.
  • It's changinglocalStorageKey of the item.
  • It is the new value after the change.

Things to note

  • Only modify between different windows/tabslocalStorageIt will only triggerstorageevent.
  • If modified in the same window/tablocalStorage, it will not triggerstorageevent.

Listen to localStorage changes in the same window/tab

In the same window/tab,storageEvents will not be triggered. We can achieve thelocalStorageChange listening.

Method 1: Use custom events

  • set uplocalStorageAnd trigger a custom event
function setLocalStorageItem(key, value) {
  (key, value);
  const event = new CustomEvent('localStorageChange', { detail: { key, value } });
  (event);
}
  • Listen to custom events
('localStorageChange', function(event) {
  if ( === 'groupID') {
    ('New value:', );
  }
});

Method 2: Use timer to poll

Another way is to poll within a certain time intervallocalStoragevalue, check whether there has been any change.

let lastValue = ('groupID');

setInterval(function() {
  const newValue = ('groupID');
  if (newValue !== lastValue) {
    ('New value:', newValue);
    lastValue = newValue;
  }
}, 1000); // Check once every second

Method 3: Use Proxy object

If you want tolocalStorageThe operation is used as a proxy, and can be usedProxyObject.

const localStorageProxy = new Proxy(localStorage, {
  set(target, key, value) {
    (key, value);
    const event = new CustomEvent('localStorageChange', { detail: { key, value } });
    (event);
    return true;
  }
});

// Use proxy objects when setting values = 'newValue';

// Listen to custom events('localStorageChange', function(event) {
  if ( === 'groupID') {
    ('New value:', );
  }
});

Example: Enable inter-page communication through localStorage listening

Suppose we have two pages, page A is setlocalStorageIngroupIDValue, page B monitorgroupIDChanges and perform corresponding logic based on the latest value.

Page A: Set localStorage and trigger custom events

const sss = (node, data) => {
  let id = ('_')[1];
  alert(id);

  ('groupID', id);
  // Manually trigger custom events  const event = new CustomEvent('localStorageChange', { detail: { key: 'groupID', value: id } });
  (event);
};

Page B: Listen to custom events and get the latest groupID value

mounted() {
  let _this = this;

  // Get data during the first load  _this.getData();

  // Use custom events to listen for groupID changes  ('localStorageChange', function(event) {
    if ( === 'groupID') {
      alert('1');
      _this.getData();
    }
  });
},

methods: {
  async getData() {
    const id = ('groupID');

    // Check if the id exists    if (!id) {
      this.$message({
        message: 'Group ID does not exist, please select a group first.  ',
        type: 'warning'
      });
      return;
    }

    try {
      const res = await ({
        page: .page_num,
        size: ,
        search: .search_field,
        groupID: id,
        ...
      });
      
      if ( === 200) {
         = ;
        (, '');
         = ;
      } else {
        this.$message({
          message: ,
          type: 'error'
        });
      }
    } catch (error) {
      (error);
      this.$message({
        message: 'The request failed, please try again later.  ',
        type: 'error'
      });
    }
  }
}

The above is the detailed summary of the implementation method of JavaScript listening for localStorage changes in real time. For more information about JavaScript listening for localStorage changes, please pay attention to my other related articles!