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>
2
  • 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? Commented May 21, 2020 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 <a href="tesVar"></a> Commented May 21, 2020 at 18:40

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Then how will I access it in HTML Page 2?
I made use of localStorage on the window object
Keep in mind that localStorage supports only string format and returns a value as a string stackoverflow.com/questions/2010892/…
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.

Comments

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";

2 Comments

Then how will I access it in HTML Page 2?
@Harold_Finch the same way you already are, <script> var testVar = someVariable; </script> but this time testVar will be defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.