-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?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 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 – mplungjan Mar 24 '20 at 09:58
  • Possible duplicate of: [How do I share a global variable between multiple files?](https://stackoverflow.com/questions/46476426/how-do-i-share-a-global-variable-between-multiple-files) – Dexygen Mar 24 '20 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 – mplungjan Mar 24 '20 at 10:08

1 Answers1

-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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320