Viewing javascript variable from any browser - javascript

I have variable in Javascript which are created by reading a number from HTML, adding a number to it and then returning it to HTML.
I want to make it so that no matter what browser/what user you are, you are seeing the latest version of the variable. Currently, if I refresh the page then the number resets to 0 (the default value). I want it so that if I update the number to 1 when someone else views it from another browser they will also see 1 and not 0.
I've seen that cookies are an option, however I thought cookies were client side only? So that would mean that only I would see the latest version of the variable.
I've seen that sessions are another option, are sessions server side? And would they do the job that I am after?
Is there another way of doing this I haven't considered?
Thanks in advance

I want to make it so that no matter what browser/what user you are, you are seeing the latest version of the variable.
You need to send your updates from the browser to a server, and then have that server relay your updates to all the other clients. There are many choices for how to do this, with various tradeoffs and complexity.
One method is to simply take that number and send it to the server. Then, on next page load, the server injects that new number into the page it outputs (or it serves it up via an API call, over AJAX, via the Fetch API, or server-sent events, WebSocket, etc.). If you do this though, you will need to decide how to handle concurrency. What will happen if two people load the page at the same time?
The general system you're describing is called Operational Transform, and this is a rabbit hole you probably don't want to go down right now. Just understand that there's no magic that synchronizes things across the planet perfectly and at the same time. Your system has to account for inherent delays in some way.
I've seen that cookies are an option, however I thought cookies were client side only?
Yes, cookies are client-side. They're sent to the server with every request, but that's not a useful tool for you, aside from session identification.
I've seen that sessions are another option, are sessions server side?
They can be, but you need to find a way to know what the user is between browsers. Normally, a session ID is stored in cookies.

Related

Sending safely JSON to server via an HTML form page

I have an html page that has a form and is communicating to a server via JSON requests, when loading (e.g. in order to remember user's previous answers) and when submit button is pressed (e.g. in order to save his new answers). Every user has a specific user_id that is located as an attribute in the url of the website. I have only HTML pages, CSS and Javascript that makes some simple functions, as well as received and sends the requests.
The problem is that the server needs an api-key for the request to happen, that I need to be kept hidden, but instead is easily discovered when the user sees the source code. I want this specific line to be hidden, but I guess this is not possible without any backend in the game.
I would like to know the easiest and fastest way to get from this state (just frontend, where every piece of information in the source code is totally insecure) to another where the api-key (at least) is not on the open.
I guess the solution is to use a server for that part but I need suggestion on the easiest transition from my code to another. I tried to use GWT, as I am a bit more familiar with JAVA backend application (but not with GWT), but seems like a big trouble, where I need to change my HTML, my Javascript and also the CSS that I have may not be useful, as well as I face a lot of problems when trying to read my parameters.
I know that it is not the best way but I do not have a lot of time to make it work, so sorry if it seems lazy (I am new to this type of programming), but I haven't found anything helpful and I cannot study for 2 weeks in order to be able to begin implementing it.
Is node.js (which is Javascript and I already have implemented the request sending/receiving in this language) easier than GWT for that matter? Will my sensitive data be secure in that way? I would be grateful if there was a similar sample, that I could start using for my implementation, as I haven't find anything that is specifically helpful for my situation.
Thanks in advance!
NodeJs is not javascript, NodeJs is specific javascript "interpreter" whose is purpose is mainly to be executed server-side. If you have an HTML page, it is likely to be loaded in a web browser (client-side), so not in a NodeJs environnement.
Everything that is hard-coded in the javascript of you web page is visible from the client, there is no way around that. So yes, you need some server-ish thing somewhere.
If you are not to manage a server by yourself or via PaaS, you can go for a serverless architecture. For instance, If you consider AWS which I know the most, you can easilly add some user management to your web page using Aws Cognito User Pool. Once a user is connected and have the good permission, he can be granted access to some other resources via a JWT token that you send along with your request.

how to maintain check boxes state across jsp pages whenever you come back on a page using javascript or jsf without storing it into database

i want my all check boxes checked whenever i come back from other pages, i want to maintain their states across pages using javascript.
I think you are asking how to store state for an individual session between requests. In this case, that state is checkbox values.
You have a choice to make first: do you want to store the data on the client (in the browser) or on your server?
Server Side
You can store this state on the server side with or without a "database" depending on how pedantic you want to be about the term.
If what you want is to avoid configuring an SQL RDBMS, you might find that the built-in storage options from most Java Servlet containers will work. In Tomcat, you can just use your Session objects as normal, but configure a "File Based Store" instead of a "JDBC Based Store." This will store session data to disk in files. Alternatively you can use StandardManager which uses in-memory storage, but does not persist session state across restarts.
Put simply, these will create a Java Map for each JSESSIONID issued by your server, and then keep the maps in memory, on disk, or in a JDBC database. For more information see: https://tomcat.apache.org/tomcat-7.0-doc/config/manager.html
Client Side
Here you have a few options as well. The driving factor is what level of browser you wish to support. If you can tolerate restricting your users to those who use a browser with HTML5 web storage and JavaScript enabled, things are pretty easy. If not, you can accomplish the same thing with a cookie.
The big downside to client-side storage is trust. Users (or software on their computer) can modify client-side storage. This goes for cookies, localStorage, and sessionStorage. Many developers forget this and introduce security vulnerabilities because of it. If this is for a real production web application, you'll want to wrap your state in an authenticator.
Here's a the first in a three article series on a way to convince your servlet container to put session state into cookies in a way that is transparent to your servlets. It is missing authentication, but you can add it by following guidance such as this bit from Rob Winch.
Now What?
Ok. You've decided to use client- or server-side storage for your checkbox values. Now what?
A simple (usually wrong) option is to store the checkbox input names and values in a map:
{"boxFoo": true,"BarBox":false}
The reason this is usually wrong is that it fails to distinguish which form your user was visiting. It means that if you apply this strategy to more than one form on your site, you'll have to worry about name collisions.
The next evolution is to have a structure keyed by form name and then field name. This would be a map like the following:
{ "formA": {"boxFoo": true,"BarBox":false},
"formQ": {"checkAlpha":true,"BetaCheck":false } }
This works, but will have annoying behavior when your users use multiple tabs. You can make that behavior more predictable for your users by using per-tab identifiers -- at the expense of space in your session object -- or by using AJAX to keep the fields in sync -- which has its own perils. Or you can do what most people do an just assume that the last submitted form overwrites the state from all previous ones, tabs be damned. That's much simpler to code, but more annoying to users.
I can propose some ways :
send http params (in hidden field) with check boxes flags which must stay checked in each new page requested by your application . You can factorize it with a function but it stays cumbersome to do.
store the check boxes marker flag in the http session. If the check boxes must stay checked in all the life of your user, it may be a suitable solution. Use may use a backing bean session for it as you use JSF.
Nevertheless, store the minimum of information in it.
store the information in a shared applicative cache to retrieve it. In this way, you stay stateless and you have not the drawback of the session if you use clustering in your servers.
There is maybe better as alternative.
You have to bind the value with a backing bean. As long as the backing bean is having the appropriate scope it will be retained on the page when you navigate to it.

Secure user authentication in offline web apps

This question has cropped up a few times in various guises, but I've not seen an answer that satisfies my requirement or fills me with much confidence. Let me set the scene.
We currently have a web application, which allows users to submit responses to pre-set questions where the data ends up in an SQL Server database, we also have a Windows application that does the same thing but works in an offline capacity; i.e. it connects to the SQL Server, downloads the questions, allows the user to complete them offline and when they next have a network connection they can synchronise the data, uploading it to the SQL Server. Great!
As part of our development strategy, given HTML 5's offline capabilities and local storage,it seems perfectly sensible to attempt to consolidate these products into a single web application. This would mean we're able to work on a single code base, and this would also enable the application to run in a browser on most devices; platform independent.
Looking into this I see a couple of potential problems, I'd really appreciate a steer on these:
Users need the ability to login, in offline and on-line modes. This could mean we download the hash's of the all users usernames and passwords, or just those that have logged in whilst in on-line mode. However, even doing this there needs to be a way to check these and given that the Javascript is readable someone could easily reverse engineer their credentials. Yes you can obfuscate the code but this isn't infallible.
The data that needs to be stored locally could be highly sensitive; contain personal information etc. Therefore this also needs encrypting, at minimum AES 256.
Am I hoping for utopia? Is this something that's just not possible at this time? Do I need to be looking at another solution and dismissing this for the time being?
Any help from you lovely people would be much appreciated.
First the easier question 2: that is perfectly possible. You can generate the key on the device and on sync send it via https to your server which can decrypt the data then.
As for question 1 I'd say an offline login is not really feasible BUT do you actually need one? Once the questionaire is downloaded (which requires online mode, so requiring login is fine) you only need to transmit it on sync, where online is again required and you can ask the user for his login there, too. I'd not recommend to download any sensible user data (e.g. hashes) to the device.
What you can do is to cache the current user only after logging in online. This would mitigate the risk of enumerating the users in your local DB.
You then need to encrypt the user's data on the front-end, I'd go with a library that does the job for you (for example, RxDB). RxDB accepts a password (which you can generate on the fly) and based on it, encrypts your DB data. The user then fills in the form (does whatever he wants) and if all of the sudden the internet is gone, the user is still able to continue his work and that work must be added as pending requests in order to do the sync. (which you already have)
When the internet is restored, you're going to check whether the session has expired for the user and if so, prompt the user to log in again and do the sync if it was the same user. If it's still there, perform the sync.
My advice based on my personal experience for the offline part.
You can create a local variable that allows the user to login once using internet for the first time then he will be able to auto login for several times as much as you decided in the local variable and when the value is 0 he will need an internet again to get another offline access for the same value you decided before.
so, in a small words. offline counter that will need an internet Only after many offline logins (when the counter decrease to 0)
Flowcharts

How would I capture the timestamp of when a link is clicked in an Email?

This may be a bit of a tricky one (for me at least, but you guys may be smarter). I need to capture the timestamp of exactly when a reader clicks a link in an email. However, this link is not a hyperlink to another webpage. It is a link formatted as a GET request with querystrings that will automatically submit a form.
Here is the tricky part....The form processing is not handled by PHP or .NET or any other server side language. It is a form engine that is hosted and managed by a cloud based marketing platform that captures and displays the form submission data (So i have no access to the code behind the scenes).
Now, if this wasn't an email I'd say it is simple enough to just use Javascript. However, javascript doesn't work so well with email, if at all (I'm just assuming there are some email clients out there that support javascript).
How would you go about capturing the timestamp for when the link is clicked without using any type of scripting? Is this even possible?
The best solution i could come up with was to have the link point to an intermediate page with javascript to capture timestamp and then redirect to the form submission. Only problem with that is that it will only capture timestamp of page load and not of the actual click activity.
There is no way to do what you want "without any type of scripting". If no scripting is done, no functionality may be added or changed.
The best option is the very one you suggested: use an intermediary page that records the request time. Barring unusual circumstances (such as a downed server), the time between a link being clicked and the request reaching the server will be less than 1 second.
Do you really need a higher resolution or accuracy than ~1s? What additional gain is there from having results on the order of milliseconds or microseconds? I can't imagine a scenario in which you'd have tangible benefits from such a thing, though if you do have one I'd love to hear it.
My initial thought was to say that what you're trying to do can't be done without some scripting capability, but I suppose it truly depends on what you're trying to accomplish overall.
While there is ambiguity in what you're trying to accomplish from what you have written, I'm going to make an assumption: you're trying to record interaction with a particular email.
Depending on the desired resolution, this is very possible--in fact--something that most businesses have been doing for years.
To begin my explanation of the technique, consider this common functionality in most mail clients (web-based or otherwise):
Click here to display images below
The reason for this existing is that the images that are loaded into the message that you're reading often come from a remote server not hosted by the mail client. In the process of requesting that image, a great deal of information about yourself is given to that outside server via HTTP headers in your request including, among other things, a timestamp for the request. Thus the above button is used to prevent that from happening without your consent.
That said, its also important to note how other mail client providers, most notably gmail, are approaching this now. The aforementioned technique is so common (used by advertisers and by other, more nefarious parties for the purpose of phishing, malware, etc) that Google has decided to start caching all mail images themselves. The result is that the email looks exactly the same, but all requests for images are instead directed at Google's cached versions.
Long story short, you can get a timestamp to note interaction with an email via image request, but such metric collection in general, regardless if its done in the manner I've outlined, is something mail clients try to prevent, at least at some level.
EDIT - To relate this back to what you mention in your question and your idea of having some intermediary page, you could skip having that page and instead you would point an image request towards a server you control

Caching client side code results across pages

In our application, we are painting navigation component using JavaScript/jQuery and because of authorization, this involves complex logic.
Navigation component is required on almost all authenticated pages, hence whenever user navigates from one page to another, the complex logic is repeated on every page.
I am sure that under particular conditions the results of such complex calculations will not change for a certain period, hence I feel recalculation is unnecessary under those conditions.
So I want to store/cache the results at browser/client side. One of the solution I feel would be creating a cookie with the results.
I need suggestions if it is a good approach. If not, what else can I do here?
If you can rely on modern browsers HTML 5 web strorage options are a good bet.
http://www.html5rocks.com/en/features/storage
Quote from above
There are several reasons to use client-side storage. First, you can
make your app work when the user is offline, possibly sync'ing data
back once the network is connected again. Second, it's a performance
booster; you can show a large corpus of data as soon as the user
clicks on to your site, instead of waiting for it to download again.
Third, it's an easier programming model, with no server infrastructure
required. Of course, the data is more vulnerable and the user can't
access it from multiple clients, so you should only use it for
non-critical data, in particular cached versions of data that's also
"in the cloud". See "Offline": What does it mean and why should I
care? for a general discussion of offline technologies, of which
client-side storage is one component.
if(typeof(Storage)!=="undefined")
{
// this will store and retrieve key / value for the browser session
sessionStorage.setItem('your_key', 'your_value');
sessionStorage.getItem('your_key');
// this will store and retrieve key / value permanently for the domain
localStorage.setItem('your_key', 'your_value');
localStorage.getItem('your_key');
}
Better you can try HTML 5 Local Storage or Web SQL, you can have more options in it.Web SQL support is very less when compared to Local Storage. Have a look on this http://diveintohtml5.info/storage.html

Categories