Not able to access cookie in javascript at path / - javascript

I am using jQuery to access/set the cookies. I have planted a cookie named CookieNo1 at path /.
I planted this using the url localhost:8080/audi.
The cookie value is stored, which I checked manually on the firefox cookies. Now when I try to access the same cookie, using the url localhost:8080/audi/products using $.cookie('CookieNo1');
This doesn't seem to retrieve the value of the cookie. It returns a null value. However when I try to write the cookie using the same localhost:8080/audi/products url, it overwrites the previous cookie value. Please help me with this issue.
All I need is $.cookie('CookieNo1') to return the previous cookie value instead of null.
Thanks in advance

You have to set the expiry date. Otherwise, the cookie is removed at the end of the session. In JQuery: $("CookieNo1", "value", {expires: 7}) (this cookie stays for 7 days).
In JavaScript:
document.cookie = "CookieNo1=value; max-age=604800";
max-age sets the maximum lifetime of a cookie, in seconds.
EDIT
Quote from comments:
#RobW I added the cookie using jquery on the page
http://localhost:8080/audi with the code $.cookie("asdftraffic",
valueToSet, { expires: 30, path: '/', secure: true }); I try to
retrieve the cookie from the url http://localhost:8080/audi/products
using '$.cookie('asdftraffic');' which returns null.
Your issue is caused by secure: true. This attribute requires the cookie to be transmitted over a secure connection (https). Remove the secure: true flag if you're not using an encrypted connection.

First you set the cookie:
var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue);
Then you get the cookie:
var getmycookie = $.cookie("mycookie");
var myvalues = getmycookie.split(",");
var firstval = myvalues[0];
var secondval = myvalues[1];
var thirdval = myvalues[2];
Should'nt be much harder.
When not specifying an expiration, the cookie is deleted on session end i.e. when the browser is closed.
EDIT: You can also specify the path:
$.cookie("mycookie", myvalue, {
expires : 10, //expires in 10 days
path : '/products', //The value of the path attribute of the cookie
//(default: path of page that created the cookie).
domain : 'http://localhost:8080', //The value of the domain attribute of the cookie
//(default: domain of page that created the cookie).
secure : true //If set to true the secure attribute of the cookie
//will be set and the cookie transmission will
//require a secure protocol (defaults to false).
});
I would think something like this would do:
var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue, {path : '/audi/products'});
Oh, and a session ends when the browser is closed, not when the page is unloaded, so a session cookie will do.

Related

Javascript cookie removed after leaving page

I'm attempting to create a cookie the first time a user visits a page on the website and store the pathname as the value of the cookie for that page for records.
I'm attempting on doing this by creating a function at the page load called GenerateCookie.
This function then checks to see if the cookie reportingpage exists or not and if it does not exist create the cookie. I would like the value to remain the same until the session is over. I am attempting to record the first page visited. So for example, if a user visits /testing-page/ I would like the cookie value to remain /testing-page/ even if they back out of the page and visit other pages, since that was the first page visited.
Currently, the cookie is created as expected with the pathname value as expected, but any time I back out of the page and visit a new page the cookie is then removed and set with the other pages pathname value. I've attempted to fix this issue by including the path= attribute when setting the cookie, but this has no effect.
How can I create a cookie and keep that same value for the entire session until the tab/browser is closed?
Here is a code snippet of my code:
GenerateCookie();
function GenerateCookie() {
// if cookie does not exist, create cookie reporting page
if (document.cookie.indexOf('reportingpage=') == -1) {
console.log('no cookie')
document.cookie = "reportingpage=https://www.testing.com" + window.location.pathname + "; path=/"
} else {
// if cookie exist, get value
console.log('cookie exist')
const name = "reportingpage"
const match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
console.log(match[1], 'value')
}
}
Storing a hundred cookies on someone's computer is really unethical, especially if it's for tracking their page visits. I'd be super annoyed if I visited a site and suddenly have a gazillion cookies to delete. But perhaps you have good reasons so if you really have to do it then use localStorage instead of cookies.
sessionStorage.setItem('someKey', window.location.pathname)

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.

PhantomJS setting cookies as Read and Write

I am trying to login to a website with phantomJS by session AUTH cookie, I finished the code for it and everything is working perfect, the problem is the website have like another login system inside with the same cookie, once accessed the other page cookie will update the security auth token, so when I add the First cookie to phantom I see that it is set to read Only because i cant access what is inside the second login system as Website is trying to update the Cookie that I manually added but unfortunately it fails because the cookie is Set to read Only.
code I am using :
phantom.addCookie({
'name': 'some name here', /* required property */
'value': 'some hash here',
'domain': 'ea.some domain here.com', /* required property */
'path': '/',
'httponly': false,
'secure': false,
'expires': (new Date()).getTime() + (10000 * 60 * 60) /* <-- expires in 10 hour */
});
I tried to delete the session cookie before my script auto access the page that needs second Auth but it just log me out because i need to have my old Session auth so it can be updated with the new session authhash.
any ideas how to make manually added cookies to be updated once requested from server side ?
I found the solution,
It appears that server actually created a new cookie with the same name and new value. not by replacing it with the new value. I searched the web for any help regarding this matter but I failed, I fixed this problem by taking the value of the new cookie and saving it to a variable, then executing phantom.clearcookies() to remove all the cookie and adding the new cookie again with the new value that I stores, It was not clean but it did the trick.

Can't delete cookies in Angular JS

I'm having lot of troubles deleting a cookie using $cookies
On logout, my code does:
var deferred = $q.defer()
$http.post( REST.logout, {} )
.finally( function() {
// finally callback is triggered both on success and error,
// since I don't really care if the server is dead or whatever
console.log('out!')
console.log( $cookies['persistent'] )
delete $cookies['persistent']
$cookies['persistent'] = undefined
console.log( $cookies['persistent'] )
deferred.resolve()
})
return deferred.promise
And the output is:
out!
"441b5deca5da04cad774a3844b6865dac8a98e91-oi=11"
undefined
However, the cookie don't bother itself to go away...
As stated in this SO question Can't delete cookie with AngularJS's $cookies, I've checked the domain, which in my case are the the same, since my web app runs from domokun.zodiac.lan and the cookie has domain of .zodiac.lan
I can add that it cannot be set again on the server side because I've cut off the communication between the client and the server, in order to test this out.
Any chance that you could see something I'm missing out would be wonderful!
tested against angular 1.2.[2-5]
One more possibility is you may be running into what I was running into. In my case I wanted to delete a cookie that had been created outside my app so it wasn't in the same domain. We intercept customers' logins through a common portal to provide their username/password. This then creates an authentication cookie that can be later read by the app, and the request is then forwarded to the app.
Anyway, the problem was that you have to be specific in defining both the path and domain of the cookie to be removed. Angular was able to read this cookie without specifying a path or domain, I was able to read it with simply:
$cookies.get("MySSOCookie");
But to remove (which I did by just overwriting with undefined when I wanted the user to be re-directed back to the authentication landing screen, such as upon logout or timeout), I had to be precise:
$cookies.put('MySSOCookie', undefined, {domain: '.myCompanyName.com', path: '/'});
Use native javascript , here some functions will help you:
//set cookies that you need
function setCookie(name, value, expires){
document.cookie = name + "=" + escape(value) + "; ";
if(expires){
expires = setExpiration(expires);
document.cookie += "expires=" + expires + "; ";
}
}
//expiration of your cookie
function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
return expr.toGMTString();
}
//get cookie with namecookie...
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
For your problem use:
setCookie(nameyourcookie,'')
I have helped you...
Can you use:
$cookieStore.remove('persistent');
http://docs.angularjs.org/api/ngCookies/service/$cookieStore
A potential problem could be if your cookie is marked as httpOnly. HttpOnly cookies cant be read by any javascript. To see if you can read the cookie, try:
$ document.cookie
in your console. If it returns an empty string despite there being cookies present in the browser, then those cookies might be httpOnly. You could also look for the HTTP check mark in the Resources tab in chrome
To get rid of the httpOnly attribute you could see if the server framework has some option for that. In nodejs/express you can pass a flag like this:
app.use(express.cookieSession({cookie: { httpOnly: false }}));
However, I don't know if that's bad practice, seeing as it seems to be some sort of session cookie we are talking about and should be handled by the server.

Does PhantomJS support cookies?

Does PhantomJS support cookies? If yes, where can I find the API details?
I am not able to figure it out after searching for a while now.
Yes, as of 1.7 Phantom has complete cookie handling, enabled by default. Cookies are retained for the duration of the process's life.
If you'd like to retain cookies across runs of Phantom, there's a command-line option cookies-file where you can specify where to store persistent cookies.
--cookies-file=/path/to/cookies.txt specifies the file name to store the persistent cookies.
In page script, you can use the regular document.cookie property. Like in browsers, this property returns a string similar to that which would be sent in the Cookie: HTTP header.
In Phantom script, you can access cookies for a page (subject to the usual origin restrictions) via page.cookies, which returns objects.
You can also access all cookies (from all domains) using phantom.cookies.
var page = require('webpage').create();
page.open('http://example.com', function (status) {
page.evaluate(function() {
document.cookie; // => "test=test-value;"
});
page.cookies; // => [{
// domain: "example.com",
// expires: "Wed, 08 Jan 2014 00:00:00 GMT"
// httponly: false,
// name: "test",
// path: "/",
// secure: false,
// value: "test-value"
// }]
phantom.cookies; // contains ALL cookies in Phantom's jar
});
To add/edit/delete cookies, use the addCookie, deleteCookie, and clearCookies methods of either a WebPage object or the phantom object.
When you use the methods of a WebPage object, you only modify the cookies that are visible to the page. Access to other domains is blocked.
However, using phantom's cookie methods allow access to all cookies. phantom.addCookie requires a domain (WebPage.addCookie assumes the current domain if you don't specify one), and phantom.deleteCookie deletes any cookie matching the specified name.
It does, through WebPage.addCookie() - which incidentally doesn't work neither for me nor someone else.
You can use this instead:
phantom.addCookie({
'name': 'mycookie',
'value': 'something really important',
'domain': 'example.com'
})
page.open('http://example.com/url/path/', function() {
console.log(page.cookies);
})
The work around I had to do was to execute javascript directly. I am using Geb and did the following:
js.exec("document.cookie='PHPSESSID=${cookie}';")
When selenium fails I always fall back to javascript for functionality.
I haven't tried it yet, but doesn't --cookies-file=/path/to/cookies.txt work?
It's the first item in API reference...
I had graded information within session recently. You should set cookie in page object, like below (coffeescript):
#page.clearCookies()
#page.addCookie
'name' : "JSESSIONID"
'value' : "0000rN3YAlVAU0xdHkKc6BEzWj9:-1"
'domain' : 'some.domain.com'
'path' : '/'

Categories