How to get the browser Cookies using JavaScript - javascript

I want to get the Browser cookies using JavaScript.I tried the below code , but i am not getting the cross domain cookies.
Here is the code:
function get_cookies_array() {
var cookies = {};
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
var cookies = get_cookies_array();
for (var name in cookies) {
document.write(name + " : " + cookies[name] + "<br />");
}
Does anybody solve this.

In most situations, you cannot read cross domain cookies, for security reasons.
Each cookie has a domain of definition, and your browser reads those to decide which cookies you can read according to which domain you're on.
If you have control of both domains, you can modify cookie settings on domain B to allow them to be read by domain A, or code a cookie getter to get the values. Be creative!

Related

HTML cookie don't create

I'm having problem of creating a cookie, I have this code:
window.onload = function() {
var value = readCookie('username');
if(value == null){
alert("null");
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
alert(value);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.
UPDATE
So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.
When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.
If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.
Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.
You are presumably loading them from a local file, and that is where the problem lies, not with your code.
Try this function for reading cookie. I've been using it for quite too long and it's working fine so far
function getCookieValue(cookie_name) {
var cookie, cookies = document.cookie.split(';');
for (var i = cookies.length - 1; i >= 0; --i) {
cookie = cookies[i].split('=');
if (cookie[0].trim() === cookie_name)
return cookie[1];
}
return "";
}
Also if you are interested you could use this function for adding cookies for 10 years.
function addCookie(name, value) {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 10);
d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}

Unable to set cookie on Internet Explorer via Javascript

I have seen alot of questions regarding this and alot of different answers, but none of them that I can see either apply to me or I have tried and they have failed.
So, essentially I have the below code:
Date.prototype.addMins = function(minutes) {
this.setTime(this.getTime() + minutes*60000);
return this;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
return c.substring(nameEQ.length,c.length);
if (c.indexOf(nameEQ) == 0) return c;
}
return null;
}
var timer_expiry = new Date().addMins(1);
var expiry = new Date().setFullYear(2030);
document.cookie = 'my_signup_clock='+timer_expiry+';expires='+expiry+';path=/;';
var asc = readCookie('my_signup_clock')
if (asc) {
alert("exists");
} else{
alert("does not");
}
I've tested this on all my browsers and the cookies are set except for Internet Explorer (including 11). Below is what I think would help rule out certain answers:
my domain is not less than 2 characters
my domain does not have any underscores in it
my cookies should be 'first-party' there are no iframes being called on the website
my website is not P3P set (but I believe this is not a requirement?)
my IE browser is default settings (I'm on Mac so I view the website via VMs or BrowserStack) - so the answer 'change your settings' won't be accepted, as I need to think of my users.
my website redirects all http into https (if that helps)
If anyone has any ideas how to troubleshoot this that would be great because unfortunately I can't see how the heck I'll be able to do this - I must be doing something wrong.
Many Thanks

How to delete __utma cookie from chrome?

I am trying to delete the Google analytic cookies from website. I am using this code to delete the cookies, But the Google analytic cookies is not remove fro the Google Chrome. How to delete the Google analytic cookies from Google Chrome ?.
function clearCookie(name, domain, path){
try {
function Get_Cookie( check_name ) {
// first we'll split this cookie up into name/value pairs
// note: document.cookie only returns name=value, not the other components
var a_all_cookies = document.cookie.split(';'),
a_temp_cookie = '',
cookie_name = '',
cookie_value = '',
b_cookie_found = false;
for ( i = 0; i < a_all_cookies.length; i++ ) {
// now we'll split apart each name=value pair
a_temp_cookie = a_all_cookies[i].split( '=' );
// and trim left/right whitespace while we're at it
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
// if the extracted name matches passed check_name
if ( cookie_name == check_name ) {
b_cookie_found = true;
// we need to handle case where cookie has no value but exists (no = sign, that is):
if ( a_temp_cookie.length > 1 ) {
cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
}
// note that in cases where cookie is initialized but no value, null is returned
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if ( !b_cookie_found ) {
return null;
}
}
if (Get_Cookie(name)) {
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + new Date + "; domain=" + domain + "; path=" + path;
}
}
catch(err) {}
};
clearCookie('__utmz','.domain','/');
clearCookie('__utmb','.domain','/');
clearCookie('__utmc','.domain','/');
clearCookie('__utma','.domain','/');
Following statement -
document.cookie = name + "=; expires=" + new Date + "; domain=" + domain + "; path=" + path;
it will make the cookie as session cookie. For deleting cookie, you should set past time. check this -
Delete cookie by name?
However, there would be one problem. Since these are google analytics cookies, so if google analytics is still enabled and working, it will set the cookies again. If you do not want to set the cookies again by google analytics, then you need to disable google analytics firstly

Client-side JS session library

I'm looking for a client-side JS library to store session variables.
I'd like a library that supports alternative storage medium, e.g. cookies when available with fallback on other techniques.
For instance, I found this one (but the last update is in 2009):
http://code.google.com/p/sessionstorage/
I'm not interested in security (apart a bit of data isolation among applications), as I'm not going to store sensitive data.
To give an example of use case, I want to display a message "Chrome user? Download the app" for chrome users, and I'd like to maintain a status in session to avoid displaying the message again to the same user. I don't want server-side sessions as I have caching enabled, so I must be able to serve the exact same page to different users.
You can use localStorage if available, and if it's not, then using cookies (or whatever you feel to):
var appToken = createToken();
try {
if (localStorage.getItem) {
localStorage.downloadAppAlert = appToken;
} else {
setCookie('downloadAppAlert', appToken, 10); // name, a string value, num. of days
}
} catch(e) {
console.log(e);
}
Then you can use some function to set your cookies - i.e. this one i just found in w3schools:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
To retrieve a cookie value by it's name - downloadAppAlert in the example - you can use the one on the w3schools link or something like this:
function readCookie(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Also, to retrieve a previously setted item on the localStorage you simply:
var appToken = localStorage.getItem('downloadAppAlert');
EDIT: Sorry, with the hurries i forgot to mention what createToken() does. It is supposed to be a random alphanumeric generator function. You can find plenty on SO, like:
Random alpha-numeric string in JavaScript?
Generate random string/characters in JavaScript
Generating (pseudo)random alpha-numeric strings
Use node-client-sessions (https://github.com/mozilla/node-client-sessions) by mozilla.

Cookie is being set.But document.cookie is null

I have set a cookie with document.cookie. The content settings in Google Chrome is showing the cookie. However, document.cookie is displaying as a blank string when printed. Why is this happening?
Here is my code
function setCookie(name,value,lifeTime,path,domain,secure){//lifetime in hours
{
var c_ = name +'='+escape(value)+'; ';
var life = new Date();
lifeTime<1&&lifeTime>0?life.setMinutes(life.getMinutes()+lifeTime*60):life.setHours(life.getHours()+lifeTime);
life = life.toUTCString();
c_+='expires='+life+"; ";
c_+= 'domain='+domain+'; ';
c_ += 'secure=secure; ';//secure
c_ += 'path='+path;
document.cookie = c_;
alert(document.cookie);
/*Just splitted the code instead of c = 'name='+value+'expires ='+life etc*/
}
A possible problem with this function is, it always sets a secure cookie. So, if you've requested/opened the page with HTTP not HTTPS protocol, the secure cookie won't be exposed.

Categories