Reputation: 85
external.js
code
var global = "parameter";
localStorage.setItem("param", global);
var storedValue = localStorage.getItem("param");
alert(storedValue);
one.html
page code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="external.js"></script>
<a href="two.html" >2nd page</a>
two.html
page code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="external.js"></script>
<a href="one.html" >1st page</a>
I want to access var storedValue
variable value on 2nd page.
Please help me to achieve this.
Upvotes: 0
Views: 854
Reputation: 336
This is so easy to get the storage value in the two.html page. Follow the code. It works.
<body>
<a href="one.html">1st page</a>
<script>
$(document).ready(function() {
var storedValue = localStorage.getItem("param");
alert(storedValue);
});
</script>
</body>
You can find the details here.
Upvotes: 0
Reputation: 443
The main thing wrong with your approach is that you are creating the localStorage item named "param" two times. So, it is not necessary. The best thing you can do is to create it on one page and then only access it from any page. LocalStorage is page independent as it is persisted in the memory, more specifically, in windows :
%LocalAppData%\Google\Chrome\User Data\Default\Local Storage.
Best approach:
const global = "parameter";
localStorage.setItem("param", global); //storing the varable in memory.
which essencially creates a variable name param in localStorage and then you can access it from the same or another page as:
const storedValue = localStorage.getItem("param"); //Accessing the item
console.log(storedValue);
Thanks for pointing out the mistake in the comments.
Upvotes: 0
Reputation: 370809
You pretty much already have it, just copy what you did in the Javascript you posted into the context of the second page:
var storedValue = localStorage.getItem("param");
alert(storedValue);
Though it's a bit nicer to use dot notation instead:
const storedValue = localStorage.param;
alert(storedValue);
Page 1 Javascript:
const global = "parameter";
localStorage.setItem("param", global);
Page 2 Javascript:
const storedValue = localStorage.getItem("param");
alert(storedValue);
Example:
Go here https://jsfiddle.net/ag2t8r0x/
and then go here https://jsfiddle.net/ag2t8r0x/1/
and you will see that the data stored on the first page is retrieved on the second page.
Upvotes: 1