How to Refer to JavaScript Variables Across Webpages in a Browser Session

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage.
Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

Persist variables between page loads

As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.

There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript


Query string

When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:

<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>

On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.

To read this data, you can use the following script on page load:

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var clicked = getParameterByName('clicked');

(Source)

Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.

In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters


Web Storage

With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.

Here I set the storage on the button click event, but you could also bind it to form submit or anything else.

$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});

Then when you load the page, you can check if it's set using this:

var clicked = sessionStorage.getItem('clicked');

Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:

sessionStorage.removeItem('clicked');

If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.

//set
localStorage.setItem('myObject', JSON.stringify(myObject));

//get
var myObject = JSON.parse(localStorage.getItem('myObject'));

Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.


Cookies

An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.

You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.

$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});

Then on page load you can read the cookie like this:

var clicked = $.cookie('clicked');

As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.

if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}

(a non-jQuery way to set/read cookies can be found right here)

I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.


window.name

Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:

window.name = "my value"

It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:

window.name = JSON.stringify({ clicked: true });

The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.

This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.

Can I pass a JavaScript variable to another browser window?

Provided the windows are from the same security domain, and you have a reference to the other window, yes.

Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.

Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.

Share data between HTML pages

why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.

To store values for a session:

sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')

or more permanently:

localStorage.setItem('label', 'value')
localStorage.getItem('label')

So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..

How can I share JS variables between pages?

Store your variable value in localstorage like this:

Page 1

localStorage.setItem("key", "yourvalue");

page 2

document.getElementById("yourVariable").innerHTML = localStorage.getItem("key");

In your case, It will be:

Page 1

<html>
<head>Page 1</head>
<body>
<p id="nom">1</p>
<button onclick="YourFunctionName()">Your Button</button>

<script>
function YourFunctionName(){
document.getElementById("nom").innerHTML = parseInt(document.getElementById("nom").innerHTML) + 1;
localStorage.setItem("key", parseInt(document.getElementById("nom").innerHTML));
}
</script>
</body>
</html>

Page 2

<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

</head>

<body>
<p id="nome"></p>

<script>
$(document).ready(function(){
document.getElementById("nome").innerHTML = localStorage.getItem("key");
});
</script>
</body>
</html>


Related Topics



Leave a reply



Submit