Cookies for different user in one browser - javascript

There is some drop down on the page of web site (user has access to this page only if he/she is authenticated) an I want to save this value to cookies and set it back to drop down when user gets back to my site.
It is not a problem to save currently selected drop down option value to cookie and retrieve it later. But I faced with some problem if I make login at the same browser by another user. It gets from cookies value what was saved by previous user.
So what is good way to separate cookies for different users from the same browser? I was thinking about create cookie with name like 'username-dropdown' but I have some doubts that it is the best solution.
I use Java with Tomcat 8.

I'm going to take a guess here that you don't need this information sent to your server with each and every HTTP request; you just need to store the information client-side (and you can send it to the server as necessary via ajax).
If so, I'd use local storage, not cookies. And sure, using the username or user ID or some such is reasonable:
// Setting:
localStorage.setItem(username + "-dropdown", value);
// Getting:
var value = localstorage.getItem(username + "-dropdown");
Or you can use brackets notation:
// Setting:
localStorage[username + "-dropdown"] = value;
// Getting:
var value = localstorage[username + "-dropdown"];
Pretty much the only reason not to use brackets notation is if you need to polyfill local storage on older browsers (there are polyfills that fall back to cookies for you), but local storage is supported on all modern browsers, and also IE8, so those browsers really are very out of date at this point.

Related

How to set cookies client-side taking into account Intelligent Tracking Protection?

According to this blog post on webkit.org, cookies set client-side using document.cookie are capped to a 7 day expiry.
I understand the rationale behind using httpOnly for sensitive cookies such as auth tokens, but if I need to store something for a long duration and have it available across subdomains of a site, then cookies are the only option, right?
With these new ITP restrictions, setting cookies client-side which should live for any longer duration of time is not going to work, so what's the best way to approach this? One idea was make a route which takes params and converts them into a Set-Cookie header and then make a request to that instead of using document.cookie. Is there a better way?
One attempt would be to use localStorage instead of cookies, technically they don't expire. The Problem however can be, that the user can decide to empty the localStorage.
Here's an example
//use this if you only need it for the current page and remove it after leaving the page
const exampleStorage = window.localStorage;
exampleStorage.setItem('currentUser', 'Manuel');
//use this if you need to keep it even after leaving the page
localStorage.setItem('glob_currentUser', 'Max');
//and finally this if you need to keep it only for the session
sessionStorage.setItem("session", "Morning")
If you need more Information about LocalStorage here are 2 helpful websites:
MDN Window​.local​Storage
The W3C Specification for localStorage

how to pop up a Notice Span when user just log in (but not just refresh to the home page)?

I do not know how to detect it is the first time that user login the web.
I thought i should write a pop-up span on the jsp that user firstly saw when he login.but the issue is then he refresh the page,the notic will show again,that is ridiculous.
I need detect if it is first login means to detect if the user JUST LOGIN or NOT REFRESH the page
how and where shall I detect if it is the first time user login ? and then i can make mind if the notice span pop up.
and I think it should use cookies or session,but which one should i use?
Maintain a field in database table that check if it is first login than show a popup and after that change the value of that field so that Popup do not appear next time.
Ex:
if($data['first_login'] == 1)
{
// show popup
}
If you want to show it only to the new user (the time user registers) you can use a table column in database where you can use it to check if the user if logging in for the first time (e.g firtsLogin the column name = 1 ). If he is logging in for the first time you show the pop-up and change the value of the field to 0.
Otherwise if you want to show to users that are logged in to a specific device for the first time you should use cookies.
I suppose that you want to detect the user logging in to your web-site the first time. There are multiple ways that you can do it depending on your desire to spend additional time writing the code, the location of your logging-in logic (client or server side), security that you want to have while proving your users with login functionality. In all cases - you would have to store the data whether the user has logged in for the first time. I think you are seeking a fast solution that will work without a big care for privacy or security as working with client-side cookies isn't the safest way to store data. The alternatives to cookies are web tokens, url query string, server-side sessions and data-base (RDBMS) storage.
Storing and retrieving the data on the client-side using COOKIES. They are the pieces stored in the user's web browser. Cookies were created to help servers remember the data about the user next time he enters the web-site. The most common usages are: to store location (if accepted by user), web-site locale (language in which the user was browsing the site), products added to cart, etc. Following that approach you can create cookie after the user has logged in to your web-site as follows:
This should be run by your JavaScript.
document.cookie = "firstLogin=true";
After having done that, you would have to add JavaScript logic that will hook-up to user's/client's COOKIE data and read up whether he has logged in the first time before.
This would probably look like a simple JavaScript cookie look-up.
var cookieData = document.cookie;
This will return all of your user's cookies that has been previously stored when he visited your web-site. It will return it as a string concatenated with "; ". If we had previously stored only one cookie, we would get firstLogin=true;
In case if you have multiple cookies set before, you would have to parse the cookie string and extract the data either imperatively by plain procedural JavaScript code or by writing the function which will be able to do that repeatedly. Detailed examples of writing such functions could be found here.

js function to go back in browser history to last browsed page of specific domain?

I need the js function to go back in history to the last pages used in a specific domain.
reason: I send people to a subdomain to see specific content-galleries (gallery.mydomain.xyz/#1etc). I need them to return to the last page where they left of from the specific tld (mydomain.xyz/pageX) after having clicked through a number of images/videos there at subdomain...
is this possible? any ideas?
thx!
It's not possible using the built-in browser history, no, because your access to that from JavaScript is close to non-existent.
What you can do instead is save the location you want to take them back to in, say, session storage (use local storage instead if this is in a different window), and then link back to that page.
More about session storage / local storage in the web storage spec, but the short version is that it stores strings in a storage area specific to your origin, so for instance:
localStorage.setItem("last-location", "foo");
...stores "foo" in local storage for your origin, with the key "last-location". You can then use getItem to get it later when you need it:
var lastLocation = localStorage.getItem("last-location");
you could use a simple get/post variable to tell where the user is coming from and store that in a session variable for later use when the user is to be returned. As far as I know you cant access the users browsing history from the browsing client with Javascript as its a violation of the sandbox design but that may have changed recently
thx both of you for the quick answer!
... I kind of see, not being a versatile coder myself. but I get the problem involved. and see session-storage is where I want to look at then...
I will have to make this a coding job given my non-skills here :-}
but now I know what to ask for. thx again.

Is there any way to access browser form field suggestions from JavaScript?

Is there any way to access the autocomplete suggestions that appear under HTML input fields in some browsers (representing previously submitted data)? Is this only available to the browser?
I ask as I want to make my own autocomplete implementation in javascript, but I want to intermingle my own suggestions with the users previous searches. A bit like how youtube does (but youtube stores all the data obviously, and it is tied to a login, there are no accounts on my website and never will be).
I was wondering more if there was a way to do it with the data stored in the users browser rather than storing all the data on my server. Is there is a way to grab the data the browser uses to present previous input to a user?
Is the data that appears in html input fields representing previously submitted data only available to the browser?
Yes - until it appears in the DOM.
Is there is a way to grab the data the browser uses to present previous input to a user?
It's a browser-specific feature, and you can't access the data [history] directly (Where do browsers save/store auto fill data). You only can disable storing anything.
I ask as I want to make my own autocomplete implementation in javascript, but I want to intermingle my own suggestions with the users previous searches. I was wondering more if there was a way to do it with the data stored in the users browser rather than storing all the data on my server.
Especially if you want to utilize all previous searches, the browser's autofill doesn't help you anyway. But yes, you can store them in the browser (on the client side) manually: Use DOM Storage, like localStorage. Though I would recommend sessionStorage only, you might run into privacy issues otherwise if everybody using a browser could see the search terms of previous users…
You can use jstorage. Jstorage lets you store up to 5Mb of data on the client side.
<script src="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="https://raw.github.com/andris9/jStorage/master/jstorage.js"></script>
<script>
/* $.jStorage is now available */
// store some data
$.jStorage.set('yourkey', 'whatever value');
// get the data back
value = $.jStorage.get('yourkey');
</script>
The only way i see this working is with help of localStorage (html5) problem that it doesn't work in ie<8
Here's an example: http://jsfiddle.net/8NZY7/

Javascript : Alert box only once when the user lands

Is there a way to display an alert box literally only once, i.e. when the user hits the website, then when they navigate through it does not appear any more?
You could for example set a localStorage propertie like
if(!localStorage["alertdisplayed"]) {
alert("Your text")
localStorage["alertdisplayed"] = true
}
Note that localStorage isn't supported by older Browsers, as noted by blazemonger - Compatibility List
An alternative would be setting a Cookie and check against its existence
If you don't know how to set / get cookies with javascript, i would suggest, reading this Article on MDN
You can check for the presence of a cookie, if not found, show the alert and set a cookie that expires after a very long time. Something like this:
if (!document.cookie.match(/(?:^|; *)alert_shown=1/)) {
alert("Hello world");
document.cookie = "alert_shown=1;max-age=" + 60 * 60 * 24 * 365;
}
PS: I am not sure if the regex is bullet proof. And cookies could be... deleted.
You could drop a cookie with a very big expiry date the first time the user lands on the site. You can then check for the existence of that cookie and only display the alert box if it is not present.
Yes. And you can use a cookie, local storage, database entry, or session variable (or a combination) to determine if they've already seen/waived the notice.
Chances are though that cookies or local storage are your only options given you're dealing with JavaScript. (Keep in mind though that local storage is still "new", not all browsers implement or support it yet).
side-note: You can also use AJAX and store the flag on the server (but this depends on your setup and what resources you have available).
Instead of an alert box, you should consider using a notification area. And then use cookies to prevent the notification are to show up more often then it should.

Categories

Resources