1

I am a .NET stack developer and I am not so strong in JavaScript. I want to pass a variable defined in the script tag of one html page and retrieve it in a different page. By the time execution control gets to the second page, the value assigned to the variable has been lost and subsequently testVar is null. I'm trying to achieve something similar to this:

In C# I would define a static global variable to achieve this.

HTML Page 1:

<script>
var someVariable = "Hello Word";
</script>

HTML Page 2:

<script>
var testVar = someVariable;
//Expecting testVar to be assigned with Hello World
</script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Harold_Finch
  • 682
  • 2
  • 12
  • 33
  • You can't pass variables this way. If on the same domain you can leverage localStorage, but that smells kinda strange. What are you attempting to do exactly in the context of a "real" example? – Phix May 21 '20 at 17:53
  • I am getting the current url assigned into `someVariable`. I want to take that and assigned it to `testVar` which will be used in an anchor tag defined in page 2 i.e Page 2 HTML will have – Harold_Finch May 21 '20 at 18:40

3 Answers3

1

You could store your variable in the global window object.

var someVariable = "Hello Word";

window.stored_value = someVariable;

The window object is global, so just use it in another script.

HTML Page 2:

<script>

var testVar = window.stored_value;

</script>

Please have a look at a similar issue:

Storing a variable in the JavaScript 'window' object is a proper way to use that object?

0

You'll most likely need to look into the postMessage API, but without knowing more about the two windows and how they are related to each other (was one opened by clicking on a link in the first, for example) it's hard to give you more direction.

dave
  • 62,300
  • 5
  • 72
  • 93
0

Inother to access external javascript in your html file, create a separate .js file e.g script.js and define someVariable in it then add the script to both html files via the script tag as so <script src="script.js"></script>.

In the script.js file add the code:

var someVariable = "Hello Word";