locked
How to detect if localstorage has been changed RRS feed

  • Question

  • User932259438 posted
                $(window).bind('storage', function (e) {
                    setInterval(function () {
                        console.log("storage");
                        var trenutnerelacije = $('#TrenutneRelacije');
                        var mesto = localStorage.getItem("mesto");
                        var ulica = localStorage.getItem("ulica");
    
                        if (e.originalEvent.key == "mesto") {
                             if (trenutnerelacije.html().split("-").splice(-1)[0].replace(/ *\([^)]*\) */g, "") != mesto) {
                               trenutnerelacije.append("-" + mesto + "(" + ulica + ")");
                             }
                        }
    
                            if (e.originalEvent.key == "ulica") {
                                if (trenutnerelacije.html().split("-").pop().match(/\((.*)\)/)[1].split(",").pop().replace(" ", "") != ulica) {
                                    trenutnerelacije.append("(" + ulica + "," + ")");
                                    trenutnerelacije.html(trenutnerelacije.html().replace(")(", ", ").replace(" )", "").replace(" ,", ", ").replace(",)", ")").replace("()", "").replace(/,,/g, "").replace(/\(\)/g, ""))
                                }
                            }
                    },1000);
                });
    This code works, but only if first time click on localstorage change and after that works in my application if has been changed.

    If used my code localStorage.setItem("mesto","test") in button in my application - works if first time click directly on my browser.
     
    What can be problem?
    Sunday, March 8, 2020 9:21 PM

Answers

  • User-1330468790 posted

    Hi, progy85,

    It seems like you are trying to use an html node "#TrenutneRelacije' to display the information when the localStorage changed.

    You should bear in mind that the 'storage' event only happened to send to notification for every document object who share the same "Storage Object" which is stored in the same storage area, but not for current one.

    It means that you can not get the notification in the current page when you have changed a storage variable.

    For more information about the "localStorage" attribute and the storage event, you can refer to below link:

    https://html.spec.whatwg.org/multipage/webstorage.html#send-a-storage-notification

    However, since the javascript is dynamical language, you can do a workaround and rewrite the original function and attach it as an event to display the change.

    More information, you can refer to below code.

    Script:

    <script type="text/javascript">
    
            //Extract from Official, Still only work for other pages
            $(window).bind('storage', function (e) {
    
                document.querySelector('#my-key').textContent = e.originalEvent.key;
                document.querySelector('#my-old').textContent = e.originalEvent.oldValue;
                document.querySelector('#my-new').textContent = e.originalEvent.newValue;
                document.querySelector('#my-url').textContent = e.originalEvent.url;
                document.querySelector('#my-storage').textContent = JSON.stringify(e.originalEvent.storageArea);
                
                
            });
    
    
            //Below code creates an event for set item operation
            var originalSetItem = localStorage.setItem;
    
            localStorage.setItem = function (key, value) {
                var event = new Event('itemInserted');
    
                event.value = value; 
                event.key = key; 
    
                document.dispatchEvent(event);
    
                originalSetItem.apply(this, arguments);
            };
    
            var localStorageSetHandler = function (e) {
                alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
            };
    
            document.addEventListener("itemInserted", localStorageSetHandler, false);
    
    
    
            function changeStorage() {
                var value = document.getElementById("textChange").value;
    
                window.localStorage.setItem("bgcolor", value);
                console.log(window.localStorage.getItem("bgcolor"));
            }
        </script>

    HTML:

    You can open multiple pages and see the display information changed along with the change of your input.

    <div>
                <input type="text" id="textChange" value="222" />
                <input type="button" id="changeBtn" value="Change Storage" onclick="changeStorage()" />
            </div>
            <div>
                <label id="my-key"></label>
                <br />
                <label id="my-old"></label>
                <br />
                <label id="my-new"></label>
                <br />
                <label id="my-url"></label>
                <br />
                <label id="my-storage"></label>
    
            </div>

    Demo: only for current page

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 9, 2020 10:32 AM