-2

Essentially I have one HTML Script, in the javascript portion of the HTML code, I have a few variables. Essentially how do I get those values to interact with another url location.

To rephrase, Let's say I have this URL, containing the variables in that script: www.example.com/stuff. Now I want to use those variables to interact with www.example.com/stuff2.

How would I do that?

John Smith
  • 57
  • 3
  • 9
  • I could be wrong but I feel like that would not be possible with just javascript. I would think you'd need a server language like PHP to do that. Can you give a little more details what exactly you are trying to do? – dmikester1 Aug 29 '18 at 21:34

3 Answers3

4

You can use locaStorage or sessionStorage for that:

In one page use:

<script>
      let var1 = "some data";
      let var2 = "other data";
      localStorage.setItem("data", {var1, var2});
</script>

In the other page get the data previously saved using:

<script>
    let data = localStorage.getItem("data");
    console.log(data.var1);
    console.log(data.var2);
</script>

Note: The same syntax works for sessionStorage

CodeMonkey
  • 1,136
  • 16
  • 31
michaelitoh
  • 2,317
  • 14
  • 26
0

You can assign variable globally

file 1

window.var1 ="value" 

file 2

window.var2 = window.var1;
Waqar
  • 826
  • 5
  • 16
  • Why would you set another window var to the already set var from the previous page? – CodeMonkey Aug 29 '18 at 21:39
  • just an example to show that variables between files can be accessible. – Waqar Aug 29 '18 at 21:41
  • Sure, but setting the first window var to a different widow var in a different file is pointless. You just need to access it, not set another one. If you are changing the data, then change the first var created. – CodeMonkey Aug 29 '18 at 21:43
  • var1 is accessed in file 2 and assigned to another variable. – Waqar Aug 29 '18 at 21:44
  • Yeah, another window var. The point is, it is cluttering the window unnecessarily. If you want to access the window var in the new file script, just set a var using `var otherPageData = window.var1;`. – CodeMonkey Aug 29 '18 at 21:46
  • Yes that's i know, but then var otherpageData = 'abc' cannot be accessed in file1. Got my point? – Waqar Aug 29 '18 at 21:48
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179058/discussion-between-codemonkey-and-waqar-adil). – CodeMonkey Aug 29 '18 at 21:48
0

If I correctly interpret your question, the solution would be to link the javascript also on the second page with <script> </ script>

JoelDoryoku
  • 364
  • 3
  • 11