Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

html - Sync a JavaScript variable between pages

I have been looking for ages trying to find a way to access a variable in another .html file. For example: File 1 (HTML)

<!--some code-->
<script>
var x; //this should equal the variable in the other file.
</script>

File 2 (HTML)

<!--some code-->
<script>
var y = 0;
</script>

How could I do it? (I can move file 2's code into a separate .js file.

question from:https://stackoverflow.com/questions/65679941/sync-a-javascript-variable-between-pages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'll have better luck storing the variable in localStorage.

Set the key in one page

localStorage.setItem('key', value);

Retrieve the value from another

localStorage.getItem('key')

The other way is to use cookies.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...