Search code examples
javascriptjquerylocal-storagesession-storage

How to access localstorage on another window in javascript


I am working with users.php page, so whenever I click on a link view_details.php infront of every user name:

1) It will create localstorage with that userid, and for every one second localstorage will be check for that user id(whether it is empty or not ) and later open new window view_details.php

2) After changes done in view_details.php I will update in table and clear localstorage from this window(view details.php).

3) As setinterval function is running in parent window(user.php) but when we clear this from view_details.php now parent window should show some alert that local storage is cleared for that user

but I am unable to access localstorage in view_details.php which was created in user.php

user.php

<script>
 $("body").on('click', '.view_user_details', function () {

 var user_id= $(this).attr("data-id");
 window.localStorage.setItem(user_key, user_id);  // localstorage is created here with user id      
 check_user_status();   // function called to check localstorage is cleared or not 

 //open view_details.php in new window 
          }
            function check_user_status() {
              setInterval(function () {

                if (localStorage.length > 0) {
                   console.log('user value:' + window.localStorage.getItem('user_key'));
                } else {
                    console.log('local storage clear');
                }
            }, 3000);
        }
    </script>

script for view details.php

<script>
     $(".save_details").click(function () {
       localStorage.clear();
        window.close();
    });
</script>

Solution

  • Try to wrap key with quote.

    window.localStorage.setItem(user_key, user_id);
    

    to

    window.localStorage.setItem('user_key', user_id);