-1

I have a problem to pass variable in js! I have two html page and each of html page has a js script. I want when click a button in first html a variable pass to another js file.

my first html(index.html) is :

// test.js

var vari;
document.getElementById("btn").addEventListener("click", function() {
  vari = 10;
  window.location.href = "./index2.html";
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p>test</p>
  <button id="btn">click</button>

  <script src="./test.js"></script>
</body>

</html>

and script of this html is (test.js):

I want when click to btn go to html2(index2.html) and and vari pass to js2(test2.js)!

my html2(index2.html) is :

// test.js
var vari;
document.getElementById("btn").addEventListener("click", function() {
  vari = 10;
  window.location.href = "./index2.html";
});

// test2.js
console.log(vari);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script src="./test.js"></script>
    <script src="./test2.js"></script>
</body>
</html>

But in test2.js vari is undefined. How can I solve this problem?

3
  • As you can see you get an error. You need to test if the element btn is there - since it is not there and not clicked, the vari is not set Commented Mar 24, 2020 at 9:58
  • Possible duplicate of: How do I share a global variable between multiple files? Commented Mar 24, 2020 at 10:00
  • @Dexygen How is that a dupe? window.globalVar will disappear at the location change.OP is not using node or react btw Commented Mar 24, 2020 at 10:08

1 Answer 1

-1

Save the variable in sessionStorage. Instead of

vari = 10;

do

sessionStorage.vari = 10;

And then you can retrieve it in test2.js:

console.log(sessionStorage.vari);

Note that storage will always contain a string. If the type matters, make sure to transform back to a number:

const vari = Number(sessionStorage.vari);

For an even more general solution, to transfer any sort of serializable data, use JSON.stringify when saving and JSON.parse when retrieving.

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

7 Comments

So sessionStorage.setItem("vari",10) can be written as sessionStorage.vari = 10; ? (I am not the downvoter)
Yes, I prefer dot notation, it's more concise
But then you do Number(sessionStorage.vari) instead of +sessionStorage.vari :)
Being concise is often over-rated. If you use the interface's setItem and getItem methods for instance, you can easily grep your code for anywhere storage is being utilized.
@Dexygen grepping for *Storage should do the same, no?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.