JavaScript initial variables and persistance - javascript

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

Related

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.

AngularJS - cleanup the whole application

In Angularjs, I keep lot of data in my services so that the server calls can be reduced and the data can be picked from local variables. This leads to data being persisted in the application till user refresh screen or close the tab. This is hazard to both security and performance as lot of data is kept in browser memory.
I want to clean up all the services on certain event (like logout) so that the cached data is cleaned up from the browser memory.
Note: I do not want to refresh the screen (window.location.reload) and I have lot of services in my application already. So need some solution with minimum effort.
unfortunately javascript doesn't provide any way to manually manage processs such as garbage collection, ecc...
Because you are in an AngularJS app neither the browser-reloading can help you.
there is just one thing that you can do in order to have a best memory management, try to reduce all variables to primitive values when you don't need them anymore.
Keep in mind, javascript clears memory when automatically some variable loses references, for example, variables defined in child scopes are destroyed when the function calls ends.

Javascript global variable life time

(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.

Javascript global namespace and dynamic property question

Say I want to have a global object which can be visible and accessible across pages(??)
// core.js
var MyLib = {}; // global Object cointainer
MyLib.value = 1;
If I define this way, then I can have access to MyLib.value in other places as long as I load the core.js.
However, if I want to add new property to object MyLib in somewhere else, say:
//extra.js
MyLib.otherVal = 2;
Then I try to access MyLib.otherVal from a different place, it is not available. I probably have some fundamental misunderstanding on how this suppose to work. I hope someone can enlighten me.
After reading the comments, I realized the scope I want is indeed across pages. Is that even possible?
thanks
Oliver
If you want to carry data across pages, there are really three major methods:
LocalStorage. See this page for a fairly thorough explanation of the concept, how to use it, and so forth. Here is a library dealing with JavaScript storage.
Cookies. Cookies can store 4KiB of data, but some users disable them.
window.name. You can store up to 2MiB of data in window.name. Here is a library that focuses on storing data in window.name; it seems fairly well-written.
You could potentially write an app to take advantage of all three of these techniques, starting with LocalStorage and falling back to window.name if all else fails.

Access URLs in the Window's History Object

Is there any way to randomly access the URLs in Javascript's History object in Safari? I'm writing an extension where I need to, on a specifically-formatted page request, capture the URL of the previous page. From what I've been able to find, the History object definition is non-standard across browsers. Safari only seems to expose its length property and the standard methods that actually move within the history. Where other implementations expose current, previous and next properties, I can't see anything that tells me Safari does the same.
I've also tried document.referrer, but that doesn't appear to get populated in this case.
I just need to display the previously accessed URL on a given page. Is there any other way to access that URL?
Thanks.
You can't really do this, at least in any white-hat way. By design. You can step the user backward and forward, but you can't see the URLs.
Less scrupulous script-writers have of course taken this as a challenge. I believe the closest they've come is to dynamically write a bunch of known comparison links to the page, and then inspect them to see if they're showing in the "visited" color state. Perhaps if you're working in a closed and predictable environment (an intranet app?), with a known set of URLs, this might be a valid approach for you. Then again, in such an environment you could deal with this on the server side with session management.

Categories

Resources