I need to get all the cookies from the browser - javascript

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

Related

localStorage not working in other host - javascript

I am developing a firefox addon. i use localStorage to save some data and retrieve.
function to check if it is available or not
if(!localStorage.getItem('font')) {
populateStorage();
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
if not then create
function populateStorage(){
localStorage.setItem('cname', name);
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'myCat.png');
}
This is perfectly working localhost but if i visit other host like google.com and try to get i am getting error not found
if(!localStorage.getItem('font')) {
alert('Not found !!!!');
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
}
is there any way to fix this issue ? or am i doing it in wrong way ?
LocalStorage is intended to be accessible only from the same host. This allows different websites to have a different scope for their data, and also ensures that one website cannot access data from another website.
From MDN,
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
From: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you need to share data across different domains, you should use server-side persistence.
From what I've undestood local storage is not cross domain solution, so this behavior is correct.
What you need to do is fallow MDN solution. I've found something like this:
// define 2 objects
var monster = {
name: "Kraken",
tentacles: true,
eyeCount: 10
}
var kitten = {
name: "Moggy",
tentacles: false,
eyeCount: 2
}
// store the objects
browser.storage.local.set({kitten, monster})
.then(setItem, onError);
(code copied from MDN > JavaScript APIs > storage )
In this solution data will be pinned to browser/extension, not to domain. But be aware, that data still will be destroyed when user clear browser cache or something like that.

How to avoid duplicate cookies

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.

How to save things using Javascript

I am making a website where you can store financial things. Just for practise. Not to publice. So far I have making the part where you can add a new list. And fill in things. But of course if I refresh the page it will be gone. So how can I save the new made list?
You could store it in the Browser via a cookie or better, localStorage. But of course if the browser deletes the "personal data" or you use a different browser, the data is gone.
Normally you would set up a server (say, PHP) and save it in a database (e.g. MySQL), even if you use the application only on your own machine.
Try using cookies or WebStorage (localstorage or sessionstorage objects). And consider using HTTPS if you working with financial info
You could use Firebase. Works great if you're only doing small things.
Basically it allows you to store data online on their servers with the simple Firebase API.
Their tutorial should get you started:
Firebase 5 minute tutorial
I am very new to learning localstorage myself and since you said "storeing in the browser" , i guess the best comtemporary and hassle and hack free method is localstorage .
Here is a accordion i made which stores the state of the accordion(weather its open or closed).
FIDDLE HERE
JS ::
$(function () {
var initialCollapse = localStorage.collapse;
if (initialCollapse) initialCollapse = initialCollapse.split(",")
console.log(initialCollapse);
$(".collapse-headings>a").click(function () {
var div = $(this).parent();
div.toggleClass("close open");
$(".collapse-content", div).toggle("slow");
localStorage.collapse = $(".collapse-headings").map(function () {
return $(this).hasClass("open") ? "open" : "close"
}).get()
console.log(localStorage.collapse)
return false;
})
if (initialCollapse) {
$(".collapse-headings>a").each(function (i) {
var div = $(this).parent();
div.removeClass("close open").addClass(initialCollapse[i])
$(".collapse-content", div).toggle(initialCollapse[i] !== "close");
})
}
});
This might be a good starting point to understanding localstorge , but if you do a google search , you'll come across a ton of useful information such as cross browser compatibility and local storage limitation and fallbacks.

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];
}
}

Get the referrer, paid/natural and keywords for the current visitor with Google Analytics

Is it possible to get the following information about the current visitor using Google Analytics API with JavaScript?
Referrer site ('Source' in GA)
Paid or natural ('Medium' in GA)
Keyword
First time/returning
Number of visits
If it's not possible with Google Analytics API is there any other easy way to do it (apart from parsing HTTP Referer, storing the visits statistics in DB etc.)?
If you're still using ga.js (the legacy version of Google Analytics tracking code), you can use the below code to generate the values you want within the browser, by reading browser cookies. (Most people will have migrated to analytics.js, which does not store the campaign information in the __utmz cookie.)
I assume you have a function called readCookie(); I tend to use the one from QuirksMode
For referral, medium, and campaign information:
var utmz = readCookie('__utmz'); //using a cookie reading function
var vals = (function() {
var pairs = utmz.split('.').slice(4).join('.').split('|');
var ga = {};
for (var i = 0; i < pairs.length; i++) {
var temp = pairs[i].split('=');
ga[temp[0]] = temp[1];
}
return ga;
})();
//vals.utmcmd: medium (organic, referral, direct, etc)
//vals.utmcsr: source (google, facebook.com, etc)
//vals.utmcct: content (index.html, etc)
//vals.utmccn: campaign
//vals.utmctr: term (search term)
//vals.utmgclid: adwords-only (value is irrelevant, but means its AdWords autotagged traffic, but it implies that medium=cpc, even though it'll be set to `(none)` or `(not%20set)`
For pageview count and visit count:
var pageviews = readCookie('__utmz').split('.')[1];
var visits = readCookie('__utma').split('.').pop() //returns number of visits
Obviously, if (+visits)===1, then its a first time visitor. (Remember: values from cookies will be strings, so you'll need to cast them to numbers to safely do numeric comparisons, even though JS is loosely typed.
You should be able to get it all from the cookies set by Google Analytics. They are stored as first party cookies so JavaScript running on a page will be able to read them. The number of visits can be obtained from the last part of the __utma cookie and the referrer can be taken from __utmz. The source is the utmcsr bit of __utmz while the medium comes from utmcmd and the keyword is utmctr.
Apparently, this doesn't work anymore. Since 2013 where use enabled SSL, all keywords are stripped out from referer URL.
From now on the only option to get some statistic (not per user) data is to enable Search Console.

Categories