'Check variable and send to home page with JS
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)?
Solution 1:[1]
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>
Solution 2:[2]
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 :
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Iftikhor |
| Solution 2 | Zouhair Dre |

