-1

hello I'm using this code to send variables to another page

    function store () {
  var first = "Foo Bar",
      second = ["Hello", "World"];
  localStorage.setItem("first", first);
  localStorage.setItem("second", JSON.stringify(second));
  location.href = "http://example/page2.html";
}

How can I check if the variable exists in PAGE2 and if no there, how can I redirect to homepage(PAGE1)?

michu
  • 3
  • 2

2 Answers2

0

You need to check localStorage in Page2 if variables are not set, localStorage.getItem will return null and if variables are null redirect to the page1

Page 2

script

<script>
    var first = localStorage.getItem("first");     
    var second = localStorage.getItem("second");

    // if first and second variables are false then redirect  
    if(!first && !second) {
        location.href = "http://example/page1.html";
    }
</script>
Iftikhor
  • 134
  • 5
0

The local storage is shared between all the pages of a website. So when you do localStorage.setItem("key","value") this key value pair is accessible in PAGE 2 using localStorage.hasOwnProperty("key") to check if it exists and localStorage.getItem("key") to retrieve its value.

On PAGE1

if(!localStorage.hasOwnProperty("key")){
    // do your logic
}

If PAGE2 is not on the same website, i.e not stored under the same url; you have no direct way to access/verify the stored value (unless you use a library).

Check the following question for the same issue :

cross domain localstorage with javascript

enter image description here

Zouhair Dre
  • 558
  • 4
  • 14