0

I want to set a variable in an external file "Variable.js" and assign it a value in a file "Page1.html" and then use that variable with that value in another file "Page2.html" Let's say I have this file "Variable.js" :

var myVar

The file "Page1.html" with this script:

<script>
myVar="Some text"
</script>

And the file "Page2.html" like this:

<html>
<head>
<script src="Variable.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p id="para"></p>
<script>
$(function() {
$("#para").text(""+myVar)
})
</script>
</body>
</html>

I want to access "Page2.html" through an <a href="Page2.html"> in "Page1.html" and the value "Some Text" to appear in that <p id="para">.Is it posible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Stefan Octavian
  • 593
  • 6
  • 17

2 Answers2

1

You should use localStorage for this.

<script>
    window.localStorage.setItem('MyVar', 'Some text');
</script>

<html>
<head>
<script src="Variable.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p id="para"></p>
<script>
$(function() {
$("#para").text(window.localStorage.getItem('MyVar') || '')
})
</script>
</body>
</html>
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27
-1

i would suggest, using cookies...

look here

so you could do something like

document.cookie = "value=Some Text";

to write the cookie and

var x = document.cookie;

to get your cookie

FalcoB
  • 1,333
  • 10
  • 25
  • It's better to use localStorage because cookies are passing to server with each request and also localStorage has better api when with cookies you will need to parse document.cookie string to receive the cookie you need. – Eugene Tsakh Oct 31 '16 at 14:57