Javascript global variable life time - javascript

(I am Javascript Beginner)
While I am learning Javascript global variable's life time, it say:
The lifetime of Global variables starts when they are declared, and
ends when the page is closed.
I read that Javascript will store the global variable into window object? And when will it be destroyed? After I close the tab in web browser?
For example:
If abc.com/page1.html create a global variable, after that in the same tab, I navigate to abc.com/page2.html will the global variable still there? How about if I navigate to another domain in the same tab, for example, another.com/page1.html?

Once window is unloaded all your JavaScript variables are lost, let's say you move from page 1 to page 2, on window leaving your variables are lost, same applies if it's on same domain or cross domain

No, the global variables aren't available from one page to the other. If you need to preserve data between page, you need to maintain state.
Maintaining state involves using either cookies or query string values. My answer to How to use JavaScript to fill a form on another page explains this in depth.

Related

Global variables accessible to other websites opened in same tab

Today I found a security issue with Chrome (or maybe other browsers I haven't tested yet). What happens is that once you open a site and then open another site in the same tab, the previous site's global variables are accessible to the current site in that tab. I have demonstrated it in this video: https://www.youtube.com/watch?v=oDFKsLaecOs
Browsers should fix this but is there any other way to protect our global variables?
This is how you can reproduce it:
I logged in to exotel.com site and they are using a name variable to store currently logged in user's name. You can use it in console and check its value.
Now go to any other site in same tab and try accessing that variable from exotel. Your name will be displayed or just add a button from HTML in inspector and on click of that display the name variable.
See the description of window.name on MDN.
You're renaming the window, not creating a new global variable.
is there any other way to protect our global variables?
Don't assign values to predefined properties unless you really mean it.
Also avoid using global variables in the first place.
When do you need to use global variables, don't make them implicit globals. Declare them using let or const.

How to keep the scope or carry vars over when changing the website with JS

I am writing a simple clickbot in JavaScript to perform repetitive tasks on a 3rd party website. It just sets input values, calls the click() method of buttons and maybe I'll have it navigate to other URLs of the same website. I initially used Firefox but got the same behaviour with Internet Explorer.
I use plain JS so far and as long as I paste in every command by myself everything works fine but here's the problem: Any time a new page is loaded (including when JS clicks a submit button) I lose all vars and functions I defined. Note that I use the web console as opposed to a <script> tag that obyiousely would be dropped when a new DOM is loaded.
Honestly, I do not entirely understand why this happens. I looked at JavaScript scope and the documentation of window.location and document.location. This site even mentioned that "In a web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded into the same window." (cf. here, but that's not the point here)
I thought it might be because strict mode might be enabled by default but that would have raised an error for name = "value" instead of silently interpreting it as a local variable.
According to this answer, any var declared outside any methods should be globals that are properties of window. Changing another propertie of window (e.g. location) should not affect them - as far as my reasoning goes - but even when assigning properties myself, they disappear when I load another page.
I suppose it could be worked around if I wrote my own website that has the site I need as an iFrame so the page my script runs on would not actually be changed. But still this is strange. Can anyone explain this behaviour? Is there another (easy) way around it?
[Edit1] Thanks to same-origine policy my proposed workaround using an own website and iframe does not work. Since the whole point of my clickbot is to be started once and click through all pages on it's own, a way to carry on data (i.e. strings including JSON) is answering this question but does not solve my problem.
[Edit2] For future visitors: After recent edits, the accepted answer does provide all information I needed. Greasemonkey is the way to go if you can use addons but the combination of bookmarklets and sessionStorage stil allow for a decent bot that performes all steps between two reloads with just one user input. Another (ugly bot possibly more powerfull) approach is to open the target website and use document.body.innerHTML and the iframe workaround. That way you bypass the same-origine policy and can build your own website as needed and still access the target website.
Regarding the lifetime of a variable this SO question goes into detail, but variables don't persist across reloads.
If you're staying within the same domain (e.g. everything happens at https://example.com, so https://example.com/page1, https://example.com/page2, etc.) then you can use cookies or local storage to keep track of values.
You can't keep track of functions easily with local storage or cookies.
Cookies and local storage are not available across domains.
I would use local storage as that is easier to interface with. So instead of:
var someVar = 'hello';
Write
localStorage['someVar'] = 'hello';
Then to use the variable:
console.log(localStorage['someVar']);
Local storage has a maximum size of 10MB. Probably enough for any automation script.
If you want to persist functions across page reloads, you should use something like grease monkey to store your user scripts.

JavaScript initial variables and persistance

I'm sure that this is a rather simple question. I am making a website with several pages. Is there a way to declare variables when (and only when) the homepage first loads, and then reference those variables later? I saw that using localStorage or sessionStorage could be of use, or declaring global variables. My precise problem is that there is a variable, hasChanged, that is false only when the web page first loads. When you click a button, it will set hasChanged to true, as well as change various things about the web page. However, whenever I visit other pages and come back, it has reset to false (whereas I want it to still be true). And, furthermore, is there a good way to have the other pages access this same variable?
SessionStorage is going to be your best bet.
if (sessionStorage.getItem('hasChanged') {
sessionStorage.setItem('hasChanged', 'true');
}
and on other pages.
var hasChanges = sessionStorage.getItem('hasChanged');
If they are truly other pages. If you have a lot of data that neesd to be shared between multiple pages. Consider Single Page Applications

Window object and properties persistance

I know the Window object is the "master" object of the browser (tab) to which everything is appended - core methods, globally declared variables, functions, even the DOM. It is above everything.
When I go to a different page in the same browser window (tab) I suppose the window object remains the same (only the dom changes), because the history and other stuff is accessible. Why I don't quite grasp is why the global variables that are attached to the window object (even using window.myvariable) don't persist.
To me the only possible explanation is because it is made this way. If so what happens, do the "non core" window elements (methods and variables that were set by the code) get erased; is every new page visit a new instance of the window object (sounds the most obvious way to me) or ...?
I can't find any useful info on this matter, usually people only know that you can't pass variables between pages (except cookies, web storage, window title), but why/how (the mechanics, not reasons) this happens are hard to come by. Thanks.
Every tab in your browser is independent window object and has its own set of global variables and thus your assumption of sharing window object is not correct. Your javascript is not and should not be allowed to SEE between tabs. If that was possible then imagine one webpage you open sniffing data and other information between tabs. Your tabs are not allowed to do your browsing history sniffing ( they can get the length of the history, I think, though).
How can the browser be secure (If you are browser's vendor)?
First, it can chose not to support certain capabilities, period such as reading client's file system arbitrarily.
Second, restrict some of the features they provide.
You might want to take a look at Same-Origin Policy and certain restrictions that are relaxed that might be helpful.
All the global JavaScript variables, functions & objects automatically become member of the window object and they are persisted as long as the the new page is not loaded/visited in the same browser window (tab).
Whenever new page is loaded or we redirect to new page within same tab then scope of these functions and variables from previous document ends and they are removed from the window object. And globally declared variables and functions for newly loaded document (from scripts associated with document) gets attached to the window object

Call Coffeescript global variable in method

My question basically refers to this example:
https://github.com/vlandham/vlandham.github.com/blob/master/vis/gates/coffee/vis.coffee
At the end of this script (on line 202) it calls the (view_type) parameter from the front end and based on the view type ('year' or 'all') renders the exact method. I need to implement the a similar strategy, but within the show_details() method of this script (on line 176)..What I precisely need is to retrieve the view_type in the show_details() method and based on the view type ('year' or 'all') decide what the content variable (in show_details() method) should display..any ideas or help will be really helpful. Thank you.
So cofeescript automatically inserts local var statements for any variable referenced inside a function (precisely to prevent global leakage that JavaScript causes by default). This means you have to explicitly pollute some global namespace which in a browser would be the window object. Nothing in CofeeScript will prevent you from assigning a field of your choice with what ever value you need and reading it back any time you need. Note that this is messy and prevented for a reason (its hard to keep this kind of code clean, also there is no window object in a server side envrionment like node.js), but it will work.

Categories

Resources