cookies dont work on Chrome - javascript

I am using a simple javascript code like this to play around with cookies
var theCookie = "login = ScottPilgrimVStheWorld";
document.cookie=theCookie;
alert(document.cookie);
I have just a simple html page with a body, a header and this javascript code.
Problem is , this is working in IE and FF but not in GC 33.0.1750.154 m. I get an empty alert box. I took a glance at the GC settings and found nothing on blocking/unblocking Cookies. What is happening? Any tips?
Thanks in advance.
EDIT
Here is another function for reading cookies
function getCookie(searchName)
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if (cookieName == searchName)
{
return cookieValue;
}
}
return false;
}
"The JavaScript Anthology 101 Essential Tips, Tricks & Hacks" by James Edwards and Cameron Adams, Copyright © 2006 SitePoint Pty. Ltd., pp145-146

Try modifying variable theCookie:
var theCookie = "login=ScottPilgrimVStheWorld;";
We must do this because as stated in W3Schools, the template for a cookie is
[cookie-name]=[cookie-name-val]; [Next is optional] expires=[expiry_date].
Also, I don't think you can just get the cookie directly like that. You have to create a function:
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
So you change your alert to something like this:
alert(getCookie("login"));
Hope that helped.

No spaces are allowed in the assignment string added to the cookie jar. Try
var theCookie = "login=ScottPilgrimVStheWorld";
Tested on chrome 33 ( 33.0.1750.154 ).
edit:
chris97ong is right in his claim that you need additional logic to extract a single cookie from the cookie jar document.cookie. if you need that, use his code or match against a regex:
var mycookie = document.cookie.replace(/(^|;)login=([^;]+)(;|$)/, "$2");

Related

Storing and Retrieving a JSON Obj from a Cookie

I have looked at many SO and haven't been able to figure out how to actually make this work using pure JS. My problem is that I need to add a 2 different urls to a json array and store it into a cookie for access across subdomains (i looked into the iframe local storage thing and it won't work for this application and the json array will be rather small so 4k cookie limit is plenty).
Now what I have is the following:
function getProject(){
var url_str = window.location.href;
var ProjectImgId = url_str.split('projectId=')[1];
ProjectImgId = ProjectImgId.split('&')[0];
var UserId = url_str.split('flashId=')[1];
var ImageURL = 'https://project-api.artifactuprising.com/project/' + ProjectImgId + '/thumbnail?user=' + UserId;
var RecentProjects = {"url" : url_str, "img" : ImageURL};
return RecentProjects;
}
The above will run on a certain page load. I want to be able to do the following with this: retrieve any existing Projects and if there isn't a match on the url, I wan to push the RecentProjects to the cookie array.
Here is where I am getting stumped. I am following w3 School's cookie set up which has worked for me in the past but I am unable to figure out how to push and pull this data using stringify and parse.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var recent = getCookie("yourRecentProjects");
if (recent != "") {
// this is where I would want to parse the JSON and then check if the getProject.url value is in the current cookie json and if it is not, push it.
} else {
recent = getProject();
if (recent != "" && recent != null) {
setCookie("yourRecentProjects", recent, 365);
}
}
}
I am pretty stumped. I have figured out how to do all this using local storage, then i realized this doesn't work across subdomains so great learning experience but not a solution. Any help would be appreciated.
well, the cookie isn't json, it's just a string with a bunch of key values.
not 100% what you are looking to do with the data, but as an example, this is taken from the MDN, example #3, as for how to parse that string to find a specific value: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie:
function doOnce() {
if (!document.cookie.split('; ').find(row => row.startsWith('doSomethingOnlyOnce'))) {
alert("Do something here!");
document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
} }
String.prototype.split() creates an array of substring segments that are delimited by the value you pass in, the Array.prototype.find() will look at each value in the array until it either finds the substring that starts with that value, or returns undefined if it finds nothing.
In you case, you'd do document.cookie.split("") to create the array of key value substrings, which at that point you can unpack the data in many ways. maybe you are just looking for the existence of the url value, in which case Array.prototype.includes() is what you are looking for.

How to Delete all Cookies on my site except for one

I'm using the following function to clear all cookies, which works.
This is clearing out the PHPSESSID too as far as I can tell. I want to retain just that one cookie alone.
I added the line: if (name == "PHPSESSID") {...
...to try and catch, and skip, altering the cookie names PHPSESSID, but it doesn't catch it for some reason.
Is there a clear reason why it's not catching, or is there a better way to achieve clearing all cookies except for "PHPSESSID"?
The Function:
function clearCookies() {
var cookies = document.cookie.split(";");
for(var i=0; i < cookies.length; i++) {
var equals = cookies[i].indexOf("=");
var name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
if (name == "PHPSESSID") {
alert("yes");
}else{
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
alert(name);
}
}
}
Hi I found the answer by using DevTool's console log instead of the cookie viewer. There's a space in front of PHPSESSID when it's set for some reason. So
" PHPSESSID" works.
Solution here: output it in the console log instead of an alert.

Removing Cookie value from browser

I know that this has been asked many times, and ive tried using the accepted answers. But sadly none of that seems to work for me in my browser(Mozilla v18.0.2).
I am using backbone for my website and im using cookies to handle user login sessions.
The following are the unsuccessful ones :
Code 1
var cookie_date = new Date ( ); // now
cookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.
// empty cookie's value and set the expiry date to a time in the past.
document.cookie = "uid=;expires=" + cookie_date.toGMTString();
document.cookie = "userName=;expires=" + cookie_date.toGMTString();
Code 2
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){
uid = c.substring(nameEQ.length,c.length);
return uid;
}
};
Any working solution for removing browser cookies??
Thanks
Roy
Simple answer
You can't.
Long answer
You can overwrite the cookie and give it an expiration time in the past.
Browsers will discard it at some point after its expiration. Until then you need to check yourself, if it has been “deleted”, e. g. with a special value or by comparing the expiration date with the current time.

Repetition via for loop based on prompt output

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.
i.e
<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
System.out.println(name + "is bad at javascript");
}
</script>
any idea whats wrong?
JavaScript is not Java. So there is no function System.out.println() unless you define it.
To output you hav either to user the DOM, console or alert.
The later might look like this:
<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
alert(name + " is bad at javascript");
}
</script>
Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.
JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().
I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
console.log(name + ' is not Java');
}​
You'll need to open up your browser's JavaScript console to see those messages.
Using document.write() is a bit more cumbersome:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
document.write(name + ' is not Java');
document.write('<br />');
}​
Demo: http://jsfiddle.net/HC3Y2/

Why isn't my cookie being set?

I am learning, please be kind if it is an obvious mistake.
/*set cookie*/
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
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;
}
function eraseCookie(name) {
setCookie(name,"",-1);
}
$(window).load(function() {
//check for the cookie
var language = readCookie('language');
//if null show red
if (language!=null)
{
$('.blue').hide();
alert('No cookie set');
}
//if null show red
else if (language!=red)
{
$('.blue').hide();
alert('The cookie is red');
}
//if blue show blue
else {
$('.red').hide();
alert('The cookie is set to blue');
}
$('#blue').click(function() {
$('.red').hide();
$('.blue').show();
setCookie('language','blue', 30);
alert('The cookie is set to blue');
});
$('#red').click(function() {
$('.red').show();
$('.blue').hide();
setCookie('language','red', 30);
alert('The cookie is set to red');
});
});
Thank-you.
Learning to use Firebug is the best advice. Another helpful tool is a colorizing editor. Even SO provides a little help of this kind. Note the line:
else if (language!=red)
"red" wasn't colored as a string, so it stood out by not standing out. Is there a variable named "red" defined somewhere in the original code? If not, this compares language to undefined.
Also, consider the lines that follow this statement:
else if (language!='red') {
$('.blue').hide();
alert('The cookie is red');
You just tested that the cookie value was not red, but you alert that it is. You make a similar mistake on the first test:
if (language!=null) {
$('.blue').hide();
alert('No cookie set');
language is not null, but the message you display suggests it is.
This isn't related to your question, but there are some simplifications you can make. For one, jQuery defines a trim method on String to remove leading and trailing whitespace. Make use if this in readCookie rather than the while (c.charAt(0)==' ') loop.
Another improvement is that the current technique of choosing an element to show by using a sequence of if blocks doesn't scale well. Your homework is to use string operations and whatnot to better handle an arbitrary number of elements, then add ".green", ".yellow", ".magenta" and ".cyan" elements. You might need to change the default behavior from showing all .color elements to hiding them. Using objects as associative arrays may also be helpful.
If you're learning the best answer to your question here would probably be some debugging tips. What are you using for debugging?
Have you tried Firebug in Firefox. http://getfirebug.com/ This will let you step through your code one line at a time and inspect exactly what it is doing, what values are really being passed to functions, and exactly what string you are assigning to document.cookie.

Categories

Resources