Retain value of variable between different html files - javascript

Fairly new to Javascript.
Imagine I have a Javascript file: Book.js, inside which I just have some global variable: var globalVar = 0;
Imagine I also have two separate html files: A.html and B.html, both of which use above script: e.g. have <script src="src/model/Book.js"></script> inside.
Now, when I opened A.html I could see globalVar was defined. Then I incremented is using console.
Then, when I opened page B.html, I was expecting globalVar to retain its value (since I declared it as global inside Book.js file and B.html also loaded Book.js) but it was undefined.
Is that expected?
Does it mean scope of global variables is inside one html page?
Apparently the second time the Book.js script got loaded, variables declared during previous invocation of Book.js "disappeared".

Is that expected?
Yes
Does it mean scope of global variables is inside one html page?
It is more akin to each page being a new program (and a reload of a page being akin to exiting the program and then running it again).
So it means you must use localStorage or something similar if you want to access variable declared in other page?
Yes. That's why localStorage was created.

Yep, the Javascript is loading in one page and cannot be changed this way, because you are reloading it from your server. Basically, each page is a different process.
However, you can use a lot of workaround like :
LocalStorage : https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Cookie : https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
And if you use a complex application, you can manage your gobal variable in back

Related

How to read a variable declared in a html file inline script to another html inline script

I have two html files e.g. abc.html & rst.html.
abc.html has inline script having a variable x declared inside it with some value.
Now I want to access the x value inside rst.html file's inline script.
Could you please let me know if this is possible.
You can't.
JavaScript does not let you access other tabs (to some extend, you may be able to access <iframes>s which could be in a separate window, but that's it and newer browsers generally prevent such accesses).
While in your browser, you have access to one set of global variables that are in that one window. Anything else is not accessible for security reasons.
The only way you would be able to do that is by using AJAX to read the second file and then search for the variable and grab the value. Good luck doing that...
The simplest for you will be to create a file, say x.js, and load that in both HTML pages. Now you will have access to all the data found in x.js.

Using a Global Variable in two scripts on same page

I want to access a common variable from two differnrt jquery scripts (which will be loaded externally to the same page). so I use
window.commonVar = 0;
My question is what are the options I've got to update it? So that both scripts have the same last updated value?
So basically if script 1 do commonVar++ , script 2 should know the current value. same way around.
You have multiple options:
Declare the variable in which ever script you load first.
Declare the variable in your main html page in a script tag before you load your other scripts
Declare the variable in a third script that you load first before the other two scripts. This script could be composed of all gobal variables that you need access via other scripts.
You could even store it in a hidden input's value.

Global variable created inside CrossRider's appAPI.ready() function not available to page?

I am trying to create a Chrome extension using CrossRider and am struggling with how to create a global variable.
My extension is essentially going to dynamically append a few JavaScript files to the page if a button is clicked, and I need it to also create a global variable and set some properties.
I tried the following:
appAPI.ready(function($) {
console.log('inside crossrider extension ready()');
window.foobar = 'barfoo';
return;
});
When I refresh the page, the message inside crossrider extension ready() is printed out to the console, so I know the extension is loaded and working, but when I try executing window.foobar or foobar in the console an error is thrown saying it's undefined.
This is my first time creating an extension, so what am I missing here? Why isn't the global variable I create inside of CrossRider's appAPI.ready() function available outside of it?
I can't find a duplicate target, so I'll explain what's happening.
I don't know the Crossrider terminology, but when a Chrome extension executes code in a page, this is called a Content Script.
However, the code does not execute in the same context as the page itself. It's called an isolated world and means, among other things, that the window object is not shared.
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
So if you want to set a variable accessible to the page, you need to set it in the page context. How? There are many ways, but they all amount to inserting a <script> element into the page.
var script = document.createElement('script');
script.textContent = "window.foobar = 'barfoo';";
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
All of that assumes that you don't control the page in question. If you do, there are other ways of communicating the the page, because DOM is shared. You can, for instance, raise a custom DOM event if the page listens to it.

Cannot get global variable in another js file

I currently have this global variable declared in javascript.js which I've imported to my main document.
var globalURL = "test URL";
When I try an alert within the javascript.js file it successfully outputs the value of globalURL.
However when I try to an alert with my current document but calling globalURL I get an error
Uncaught ReferenceError: globalURL is not defined
I'm I doing something wrong here? I followed the example here but still it doesn't work for me. Can I access variables from another file?
UPDATE:
I have included my javascript.js file with my current document, so I don't think the error is there. Otherwise the first alert function within the javascript.js wouldn't have run at all.
In your HTML file, you are probably loading the file that you use globalURL before you load the one that sets globalURL
Open your browser's developer section and there scripts tabs. Observe that both js files are loaded into memory. I believe one of them is not loaded. Global valiarbles in js are available in combined space.
Another possibility is that you might be declaring it from inside of a function somewhere. If you want to declare a global variable from inside a function, try leaving off the var at the beginning. This would look like
globalURL = "test URL";

How to create a global variable that can be accessed from external javascript as well as asp.net website

In my website we have one common javascript where we will assign value to a variable i want to call that variable in my aspx page as well as in another javascript file can anyone let me know how to declare that kind of varibale globally .
you can write a common javascript file which will contain all the global variable(assuming they are constant and they wont change).
if you have the variable value as non constant, there is noway that you can put it in a javascript file, instead you can use the local storage, cookies to store the information and use it across your javascript files.
the life time of a javascript variable is limited to the page, you navigate to other page its lost.
If you do not expect any page to assign new values in your common javascript, you can add it to the page as the first header script :
<script type="text/javascript" src="script/common.js"></script>
If you want to assign new values and reuse them, it is possible if you let ASP.Net generate your javascript file by passing a query string to the next page's URL, then in that page's script tag. Let's assume that your common variable is called "myGlobalVar". Supposing that "common_js.aspx" dynamically generates your variable definition, you can have something like this :
(URL : www.mysite.com/products.aspx?myGlobalVar=3)
<script type="text/javascript" src="script/common_js.aspx?myGlobalVar=3"></script>
This will keep track of your new js value whenever an update has to be made.
But if so, you may likely want to use a cleaner way to achieve what you want, for example : using the context manager instead of common js vars.

Categories