Reputation: 97
I have tried out a scenario which I'm confused of. This is may be javascript 101, but I'm missing a point here.
Assume you have JS library which has a global variable defined. Also it has two functions called setData and retunData .I have separate html with a script within it's Head tag. This HTML file imports above library.
Now on the html I have a text field with two buttons.Buttons are send data and view data. The flow is, user type something and click send Data button. On its onClick I'm getting the text value and pass it to above JS library setData function which sets data to global variable. When i click the view data , on it's onClick it will call the returnData functio of JS Library and I'm alerting the value.
My question is, if I run my html on two browsers , and from one browser if i set the value "ONE" , on the same browser when i retrieves it says "ONE". On the second browser if returned the value it should be "ONE" because that variable is global and value is already set by first browser.
But it works as two requests. it won't override the global variable value. I know it should be the ideal case. But WHY? That's a global variable right? I hope my question is clear.
on the jsLibrary i have this.
var checkVal;
function setData(val){
checkVal = val;
}
function viewData(){
return checkVal;
}
My html is this.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="js/jsLibrary.js"></script>
<script src="js/jquery-2.1.1.min.js"></script>
<title></title>
<script type="application/javascript">
function sendData(){
var val = $("#idTextVal").val();
setData(val);
}
function viewData(){
alert(returnData());
}
</script>
</head>
<body>
<input type="text" id="idTextVal">
<input type="button" id="idConnect" onclick="sendData()" value="SEND">
<input type="button" id="idChecj" onclick="viewData()" value="VIEW">
</body>
</html>
Upvotes: 1
Views: 269
Reputation: 193261
WHY? That's a global variable right?
It is global, but for this particular tab/page instance. If you open that same page in other tab, javascript engine will initialize all variables, because it doesn't know that you have other tab.
In your case you have multiple options. Perhaps, the most straightforward is to use serverside storage to preserve state. Or you can use simple cookies/localStorage approach, they are also shared by all pages on the same origin. I would go with WebStorage as simpler:
function setData(val) {
localStorage.checkVal = val;
}
function viewData() {
return localStorage.checkVal;
}
Upvotes: 2