I am trying to make the localstorage.setitem(key,value) method dynamic to do some custom stuff. But it doesn't seem to work? Is this supported in LWC framework?

Here is my HTML file

<lightning-button class="slds-m-left_xx-small,slds-m-top_large"
                                    label="Reset" onclick={resetFlags} style="margin-left:5px">

and JS File is below

        const originalSetItem = localStorage.setItem;
        localStorage.setItem = function(key, value) {
            console.log(`I am inside the custom function`);
            const event = new Event('itemInserted');
            event.value = value; // Optional..
            event.key = key; // Optional..
            originalSetItem.apply(this, arguments);


        localStorage.setItem("foo1", "bar1"); // Pops an alert

My basic goal is, when an event changes local storage on one browser tab it should be notified on the same tab to the same component but on a different salesforce tab. The above was the approach suggested in here

1 Answer 1


The linked solution only works within the same browser tab. It's also generally unnecessary in modern code; just use window.postMessage to write a message to yourself if you're in the same tab, or use lightning-message-service. If you want to message to a different tab, using window.addEventListener('storage', handler) and localStorage.setItem(key, value) should also work, as long as the components are in the same namespace.

  • Hi @sfdcfox, what I am trying to achieve is also for the same browser tab as well. I tried to use lightning message service. Our use case is in Service console app where you can open multiple Salesforce tab in one browser tab. I put my component (which is both publisher and subscriber to the channel) in two tabs. Loaded my components in both tabs and when I publish message in one tab the component in that tab is only able to read the message but not the component in the other tab. Not sure what I am missing here? Really appreciate your help Sep 18, 2021 at 6:03
  • @Sfdxfox I figured the issue with LMS. I forgot to specify the scope of the published message to application_scope. Thanks for your help! Sep 20, 2021 at 19:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .