How to avoid duplicate cookies - javascript

In my application I set a cookie using jQuery Cookie Plugin v1.4.1 (https://github.com/carhartl/jquery-cookie) like this:
$.removeCookie("Test_Cookie");
$.cookie("Test_Cookie", "xxx");
I want this cookie to only exist once but under some circumstances the cookie exists twice.
How is that possible and what is the best practice to make sure a certain cookie exists only once?

You can use the String.prototype.split() to convert document.cookie to an array of key value strings (key=value), then you can iterate over these, split them, and if the key is the value, break. Please see below for an example:
function checkCookieExists( cookieName ){
var cookies = document.cookie.split(';'); //returns lots of these: key=value
var toCheckCookie = cookieName; //checks if this cookie exists
cookies.forEach(function( cookie ){ //foreach cookie
var key = cookie.split('=')[0]; //the key cookie
if (key.toLowerCase() === toCheckCookie) //if the current key is the toCheckCookie
{
return true;
}
});
return true;
}

One way to get duplicate cookies is to have a page at company.com and another page at dev.company.com. Then requests to dev.company.com will get cookies for domains .company.com and .dev.company.com. The HTTP responses from dev.company.com can never change the cookies the browser is storing for company.com. This means you cannot "clear" all the duplicate cookies with HTTP response from dev.
This can be frustrating because often the library to handle cookies will only return a single cookie for a key. A valid HTTP cookie header is "Cookie: zyx=data1; zyx=data2" Then your library will return only one of these, likely the first one.
A common solution for this is to use a different cookie key for different domains: "Cookie: dev.company.com-xyz=data1; company.com-xyz=data2"
Another solution is to get the HTTP Cookie header, parse it while handling multiple cookies and use the first one that is valid. Like with a valid auth or a valid JWT.

Related

How to properly control the google analytics cookie from javascript?

Currently I have set up the cookie prompt to override document.cookie set method, so that it stores non-required cookies and waits for user input (which cookies the user allows to use in the web page) to decide about other cookies.
Code looks something like this:
const originalSetter = document.__lookupSetter__('cookie');
function newSetter(cookie) {
if (isRequired(cookie)) {
originalSetter(cookie);
}
else {
//store the cookie and decide later.
}
}
document.__defineSetter__('cookie', newSetter);
Since the google analytics cookie is not a required one (at least in my page), is this the correct approach or is there another way to do this?

Cookie not being deleted after session closed

I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false any idea why?
I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};
document.cookie = ... sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)
I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem() or docCookies.removeItem() work incredible well.

how to localhost saved values check using javascript

how to localhost saved values check using java script,Button on click based saving one value,after page refresh want to check check value save,How to check
Dear you can use SESSION variable for it. You can store checked checkbox value in an index on array and that array stored in Session Variable. So by this way you will get all checked values and can use anywhere.
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in name/value pairs, and a web page can only access data stored by itself.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Example:
function getItem(key){
if (!hasLocalStorage || !key) return;
return localStorage.getItem(key);
}
function setItem(key, val){
if (!hasLocalStorage || !key) return;
localStorage.setItem(key, val);
}
function hasLocalStorage () {
return typeof window.localStorage !== 'undefined';
}
//to store an item
setItem("itemKey", "itemVal");
//to retrieve an (the above, in this case) item
var fetchItem = getItem("itemKey");
Did you try to store that value in cookies?

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

I need to get all the cookies from the browser

I need to get all the cookies stored in my browser using JavaScript. How can it be done?
You can only access cookies for a specific site. Using document.cookie you will get a list of escaped key=value pairs seperated by a semicolon.
secret=do%20not%20tell%you;last_visit=1225445171794
To simplify the access, you have to parse the string and unescape all entries:
var getCookies = function(){
var pairs = document.cookie.split(";");
var cookies = {};
for (var i=0; i<pairs.length; i++){
var pair = pairs[i].split("=");
cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
}
return cookies;
}
So you might later write:
var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"
You can't see cookies for other sites.
You can't see HttpOnly cookies.
All the cookies you can see are in the document.cookie property, which contains a semicolon separated list of name=value pairs.
You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.
To retrieve all cookies for the current document open in the browser, you again use the document.cookie property.
Modern approach.
let c = document.cookie.split(";").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});
console.log(c);
;)
Since the title didn't specify that it has to be programmatic I'll assume that it was a genuine debugging/privacy management issue and solution is browser dependent and requires a browser with built in detailed cookie management toll and/or a debugging module or a plug-in/extension. I'm going to list one and ask other people to write up on browsers they know in detail and please be precise with versions.
Chromium, Iron build (SRWare Iron 4.0.280)
The wrench(tool) menu: Options / Under The Hood / [Show cookies and website permissions]
For related domains/sites type the suffix into the search box (like .foo.tv). Caveat: when you have a node (site or cookie) click-highlighted only use [Remove] to kill specific subtrees. Using [Remove All] will still delete cookies for all sites selected by search and waste your debugging session.
Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.
export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});
If you develop browser extensions you can try browser.cookies.getAll()
What you are asking is possible; but that will only work on a specific browser. You have to develop a browser extension app to achieve this. You can read more about chrome api to understand better. https://developer.chrome.com/extensions/cookies

Categories