Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global variable does not persist when navigate to another page (which also uses same js file) [duplicate]

Tags:

javascript

I have shared js code like this in angus.js

var g_colour;

function getcolour() {
  return g_colour;
}

function setcolour(colour) {
  g_colour = colour;
}

Which is accessed by html pages 1 and 2 like this:

1.html:

<html>
<head>
<title>Global javascript example</title>
</head>
<body>
<a href="2.html">Page2</a>
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>

2.html:

<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
<a href="1.html">Page1</a>
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>

If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.

I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?

like image 841
Angus Comber Avatar asked Feb 17 '26 00:02

Angus Comber


1 Answers

JS variables never have been persistent, but there are two ways around this:

  1. Cookies
  2. Storage

Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.

Instead, you should probably look at the Storage option.

Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname

These values are saved across pageloads, but not sent to the server.

like image 74
Niet the Dark Absol Avatar answered Feb 19 '26 13:02

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!