Reputation: 471
I need to refer a global variable across multiple html files,each of the multilpe html file is referring to a common js file.
index.html sub1.html sub2.html
in each of the html pages the js is included in the head tag
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="/css/Main.css" type="text/css"/>
<script src="/js/Main.js" ></script>
</head>
Navigation from one html to other html is from a js function like.
say from index.html to sub1.html
window.location.href='/forms/sub1.html';
I have declared a global varibale globalCount, to check how many navigations have been done in the global scope of the Main.js
var globalCount=1;
and incremented in the navigation function.
But for each of the html page the globalCount variable is reinitialized to 1, even though the Main.js is NOT downloaded multiple times.
I have tried declaring through window.globalCount, no luck.
Any easy way to have a common global variable across multiple htmls but in the same js file.
Hope you understand the question.
Upvotes: 0
Views: 1879
Reputation: 150070
Your JS file (or any JS file) is not downloaded and run on its own; it doesn't act as a sort of controller that stays in memory while the HTML pages are loaded and replaced. The scope and life-cycle of code in included JS files is essentially the same as for code included inline in an HTML page so when you navigate to a new page the JS is gone even if the new page references the same include file. As you've seen.
If you use a cookie to store your variable's value as per Matt Lo's answer your JS script can get the value from there. Or you could add it as a query string parameter at the end of each page's URL (like 'sub1.html?globalCount=' + globalCount
) and access it from there.
(Or you could submit the values and use some sort of server-side technology to echo them back in the new page, but that is overkill.)
Upvotes: 2
Reputation: 5741
Simple! Use a cookie https://developer.mozilla.org/en/DOM/document.cookie
This will allow you to access your variable through the user's system.
Upvotes: 2