Search code examples
javascriptgetsetlocal-storagetypeof

setting a variable on one page and checking if it was defined on another


Ok so I have 2 pages, say default and page2. In page 2 I have a button (which sends me back to default) and an onclick function which I have written which sets a variable to be stored in local storage. What I need is for this variable (set on page 2) to only be defined when the user clicks the back button. I had the following code in my default page:

if (typeof window.localStorage.getItem('value2') == "undefined") {
             console.log("undefined");
         }
         else {  
             console.log("defined");
         } 

And on my home page I have the following function written:

function homeClick(url) {
            //var id = parsed.ClientID;
            //window.location = url + "?src=" + 6;
            window.location = url;
            window.localStorage.setItem('value2', UDID);

        }

And this is the html of the button:

<button id="home" onclick="homeClick('/default.html')" style="position:relative; z-index:0;  height: 32px; width: 100px; left:-12px; top: 0px; display:none">Home</button>

As it stands I get defined in the console both times. Any ideas?


Solution

  • Assign the value before redirecting

    function homeClick(url) {
                //var id = parsed.ClientID;
                //window.location = url + "?src=" + 6;
                window.localStorage.setItem('value2', UDID);
                window.location = url;
    
    }