Global variables in JavaScript with multiple files - javascript

I have a file called index.php. With script tags, it references index.js.
I also have a file called payment.php. With script tags, it references payment.js.
I need to set a variable called seatSelected in index.js and then use it in payment.js. However, I do not want to reference index.js in payment.php.
I have tried to make a file called globals.js, reference it in index.php before index.js containing the following:
var selectedSeat;
function setSelectedSeat(seat){
selectedSeat = seat;
}
function getSelectedSeat(){
return selectedSeat;
}
And setting the value in index.js with:
setSelectedSeat("test");
Receiving it in payment.js with (referencing globals.ks in payment.php above payment.js):
alert(getSelectedSeat());
But it alerts 'undefined'. Am I doing something wrong? How can I reference this variable without referencing the file it is changed in?

You cannot access variables created from another page.
You could use localStorage with cookies as fallback.
function setSelectedSeat(seat){
if(localStorage) {
localStorage['selectedSeat'] = JSON.stringify(seat);
}
else {
//add code to store seat in cookie
}
}
function getSelectedSeat(){
if(localStorage) {
return JSON.parse(localStorage['selectedSeat']);
}
else {
//add code to retrive seat in cookie
}
}

You are trying to persist the state of variables while transitioning from one page to another and your application seems to have data that would require session expiry, I suggest you use sessionstorage. With help of polyfills you can give sessionstorage support till IE6 browser.
Benefit of using SessionStorage over LocalStorage
Session Storage persists the data only for a particular tab/window and the data is lost when the tab/window is closed.
As the data gets expired automatically you don't need to worry about session expiring.
You can expire your session at your will as well.
The data persists on page refreshes.
But Remember with sessionstorage you can only store strings key-value pattern. And you need to use JSON.stringify and JSON.parse method to store your complex objects in browser memory.
Here you can find a list of polyfills that you can use to provide the support of sessionstorage in non supporting browsers : https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-storage-localstorage-and-sessionstorage
Also you can read the following article to understand sessionstorage and localstorage in a better way: http://diveintohtml5.info/storage.html

Related

How to save the last state of sliders after page reload

I have this network visualized using d3 and angular. Here is the link to the visualization.
I wanted to save the last state of the network so that even if I refresh the page it will show the last state. But don't know how to do that.
I read that it can be done using sessionStorage or localStorage but I can't seem to figure it out for my visualization.
I tried this by setting my JSON data to the sessionStorage and then getting it:
if (sessionStorage) {
sessionStorage.setItem("myKey", myJSON.toString());
}
if (sessionStorage) {
sessionStorage.getItem("myKey"); // {"myKey": "some value"}
}
and I also tried it like this:
localStorage.setItem("networkGraph", networkGraph);
var networkGraph = localStorage.getItem("networkGraph");
but it's not working. Is this the right way to do it?
Any help will be highly appreciated!
Are you sure that you need sessionStorage and not localStorage? In the case of sessionStorage saved data will be deleted when a browser tab with your app becomes closed.
You can write localStorage.setItem('inputLayerHeight', vm.inputLayerHeight); in your onChange handler to remember inputLayerHeight and Number.parseInt(localStorage.getItem('inputLayerHeight')) || 15 to restore the inputLayerHeight at value property of vm.inputLayerHeightSlider object. The same approach can be used for the other values to keep.
Your attempt is almost right. The only thing you need to change is the usage of localStorage. Simply add window or $window (more 'angulary' way to access window variable) variable like so:
$window.localStorage.setItem("networkGraph", JSON.stringify(networkGraph));
Also, I recommend using angular-storage if you're looking for an easy way to work with local storage. It makes things less painful :)
I think the problem might be related to the way you are storing data on your local storage. You are saving data as a string however I think that d3 doesn't recognize strings as valid data options. So instead you should do something like this:
if (sessionStorage) {
// Parse the data to a JavaScript Object
const data = JSON.parse(sessionStorage.getItem("myKey"));
} else {
// Fetch data...
// Set sessionStorage or localStorage
sessionStorage.setItem("myKey", myJSON.toString());
}
You can rearrange the logic as it might suit you but the idea is that in the end you should use JSON.parse() when getting the data from storage.

Get data from localStorage (google script)

In my app for google spreadsheet I save some params in localStorage in one function. And in another function I need to retrieve them. Of course, I can create modeless dialog or sidebar, when will be my html code and js, but this second function only refresh current sheet, so I don't need UI. Also I know, that server side doesn't have access to localStorage.
Here is my abstract code:
server.gs:
function menuItemClicked()
{
// when we click on item in addon menu, this called
// and load 'client.html'
}
function refreshCurrentSheet(params)
{
// called by 'client.html'
// do something else with params...
}
client.html:
<script type="text/javascript">
google.script.run.refreshCurrentSheet( localStorage.getItem('var') );
</script>
I didn't find answer in API, how to do that(
Question: how can I load html and execute js without visible UI ?
P.S. Saving these params on server-side in cache is not a solution, because I often use and change them in client
You can use either Properties Service or Cache Service. Both provide localStorage functionality allowing you to store key value pairs (string type only). If you'd like to persist data between function calls, Cache is probably the best option
More on Cache Service
https://developers.google.com/apps-script/reference/cache/
More on Properties Service
https://developers.google.com/apps-script/reference/properties/

How to make a variable in content script which is accessible on all the pages

I have a content script in which there is a script called myscript.js, now I have made it in such a way that if a page on google.com loads then setA of modifications are done otherwise setB of modifications are done. Now I want a variable which is accessible from all the webpages that open on that browser. like we have static variables in java, the same variable is accessible to all the objects of the class, using that analogy here the static variable is the global variable and objects are webpages that load
If you need something available in every instance of content scrips (and other extension pages too), you can use chrome.storage API.
A slight downside is that the API is asynchronous:
var myValue;
chrome.storage.local.get({myKey: "myDefault"}, function(data) {
myValue = data["myKey"];
// You can use myValue here..
});
// ..but not here
This is fine if you're okay with chaining asynchronous code; otherwise, you can maintain a local copy and update it on onChanged instead of using get every time:
chrome.storage.onChanged.addListener(function(changes, area) {
if(area == "local" && changes["myKey"]) {
myValue = changes["myKey"].newValue;
}
});

Update a global variable

I have a problem with my 2 js files and two html files main.html and log.html with only one button that redirect to main.html and throw an alert
JS File 1:
I have a global variable
context= {};
and a main:
function main() {
if (typeof context.active != 'undefined')
alert(context.active);
}
JS File 2:
I have a function
function setActive() {
context.active=true;
window.location.href="main.html";
}
When I click on my button,it does redirect me to main.html however there is nothing that happens (so it's undefined). I ve done several tests and the button works. Why is it not updating context.active?
Thank you.
Try something along these lines, you need to check and account for certain situations.
JS File 1:
context = {};
Main HTML: (we are checking to make sure that context.active has been assigned. You will get an undefined message if context.active has not been assigned as a property of context)
function main()
{
if (typeof context.active != 'undefined')
alert(context.active);
}
JS File 2:
function setActive() { context.active=true; }
The moment your browser redirects the Javascript variables are essentially erased. A full page reload (redirect) results in a clean slate.
If you are trying to persist data on the client side across page loads then you will have to use either cookies or session storage.
document.cookie - link
sessionStorage - link
Each approach has it's pros and cons so be sure to read the docs and check support for these APIs in the browsers you plan to support.

Javascript storing/state of global data/object

Is there a way to store global data in the window object such that the data can survive page reloads/refresh. So lets say I assign my global data/object -
window.myObject = myProductObject
And the user refreshes/reloads the page or may be jumps to another page of my website. Is window.myObject still available after the page reload?
NOTE -: I cannot store the object in a cookie, since its a object, I mean it could be a reference to another custom object or it could refer to another "window" object which has opened via "window.open"
Use the window.top.name hack
var data = window.top.name ? JSON.parse(window.top.name) : {}
...
window.top.name = JSON.stringify(data)
window.top.name persists across page loads
I recommend you use an abstraction like lawnchair instead though
You CAN save objects in cookies. But localStorage is better. Is similar to a cookie but you get 5Mb to use.
You have to JSON encode/decode if you save objects instead of strings, but that is easy with a wrapper on localStorage or cookie.
Here is a really simple wrapper for localStorage (you have 5Mb to use):
var Storage = {
set: function(key, value) {
localStorage[key] = JSON.stringify(value);
},
get: function(key) {
return localStorage[key] ? JSON.parse(localStorage[key]) : null;
}
};
And you can use it like this:
$(function() {
var defaultValue = {param1: 'value',counter: 0 },
myObj = Storage.get('myObj') || defaultValue; // get the obj from storage or create it with default values
$('body').html('counter: ' + myObj.counter);
myObj.counter+=1; // increment counter
Storage.set('myObj', myObj); // save it to localStorage
});
​
You can try it on this jsFiddle: http://jsfiddle.net/guumaster/LytzA/3/
You could try storing a string representation of your object in a cookie, provided the object is made up of values only (no methods), eg
var foo = { a: "a", b: "b" };
document.cookie = "foo=" + JSON.stringify(foo);
There's a good cookie reader / writer example here - https://developer.mozilla.org/en/DOM/document.cookie
I'm not sure how this fairs cross-browser. I at least got it to work in chrome, firefox and IE9 and IE8/7 in compatibility mode, but you will get warned about popups. You can detect if popups are being blocked and refuse to load anything until they are enabled for your site. See Detect blocked popup in Chrome
I'm using jQuery to bind to the beforeunload event, you can use your preferred solution.
jQuery(function ($) {
$(window).bind('beforeunload', function () {
window.open("", "_savedata", "titlebar=0,width=100,height=100").saveData = window.saveData;
});
var store = window.open("", "_savedata");
window.saveData = store.saveData;
store.close();
});
Example: (refresh the page a few times)
http://jsfiddle.net/hZVss/1/
And as requested by #Raynos - persisting closure state - something you can't serialise (works in firefox and chrome at least, IE calls it a security issue, but might be something to do with how jsfiddle is using frames)
http://jsfiddle.net/ght9f/2/
Disclaimer: I wouldn't vouch for the elegance of this solution. I was merely curious about persisting object state using popups. Serialising your object to JSON and storing it in a client side store is much better (#Raynos would recommend lawnchair https://github.com/brianleroux/lawnchair/). You should avoid cookies if you can as this data gets posted back to the server, which might not be ideal.
If your main objective was to persist references to popup windows you can actually do this by giving the popup a name. This is exactly how I am persisting my reference to the popup that I create on refresh.

Categories