Javascript cookie value is lost after loading another page - javascript

I have a page with a hidden form where a value is echoed by php.
With javascript/jQuery I pick up the value and store it in a cookie. The user is redirected to an external page, then is redirected back to my site on a different page. On this page the cookie value is "0" (the value is lost).
Update: The last page is in a directory above the page where the cookie is set. I set the "path" on the cookie but it still doesn't work.
So - first I do the redirect (by submitting a form) , then I set the cookie:
function sendPostRequest(){
var $ = jQuery;
document.myform.submit(); //submitting the form
var now = new Date();
var time = now.getTime();
time += 144000 * 1000;
now.setTime(time);
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + now.toUTCString() +
'; path=http://domain-name/the-last-page/';
console.log(document.cookie); //the cookie is set
alert($('#member_input').val());
}
The cookie is set as it should after the redirect.
When the user comes back from the external page to the new page , it shows member_id=0 . So the value is lost.
I suspect something is wrong with the "path". I have tried path=/before. The initial page has a path like: http://domain-name/directory/the-first-page/ .
Update 2:
Another info that may be relevant is that the intial page is not SSL-encrypted, but the external page is SSL-encrypted, and the final page isn't.

var d = new Date();
var days=5;
d.setTime(d.getTime() + (days*24*60*60*1000));
var expires = ""+d.toUTCString();
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + expires +
'; path=/';
use date to set the expiry of the cookie and use this formula to set number of day for the expiry

Related

Cookie collision: is it possible to distinguish between parent domain and subdomain cookies in Django and Javascript?

I have built a bunch of Django websites at a single domain:
example.com
site1.example.com
site2.example.com
site3.example.com
They are supposed to be completely independent — used by different people for different purposes.
However cookies set by example.com are given priority by Django, and values set by site1.example.com, site2.example.com etc. are ignored if the parent domain has set a cookie with the same name.
How it works:
When the first page is loaded, it sets a cookie so the server knows to send a computer page or a mobile page with the next request.
The Django program builds the correct version based on the cookie value.
When site1.example.com loads, it sets a cookie asking for the mobile version. But then the Django program sees the value set by example.com and ignores the correct cookie.
So, I need a way to do one of the following:
prevent site1.example.com from reading the cookie of example.com
differentiate in Django the domain associated with the cookie so I can tell that the value is wrong
find a way to set a parent domain cookie in Javascript that makes it inaccessible to subdomains (I'm not using www)
If I can't find an elegant solution, I will likely end up changing the cookie name to vary with the domain name.
I know that I could use the session framework, but apart from this particular issue, everything works great. I would really like to avoid modifying my existing system, though obviously I will if I have to.
[update] Here is the cookie-setting function:
function setCookie(cname, cvalue, exdays) {
var domain = window.location.hostname;
if (exdays > 7) exdays = 7; // max in Safari
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var name = cname + '=' + cvalue + '; ';
var expy = 'expires=' + d.toUTCString(); + '; ';
var domn = '; domain=' + domain + '; ';
var path = 'path=/; ';
var secu = 'samesite=lax; secure;';
var complete = name + expy + domn + path + secu;
document.cookie = complete;
}
Since you say the websites are supposed to be completely independent the 3rd solution you propose seems most sensible. You should not be setting cookies in such a way that they are accessible by subdomains. Currently you are specifying the domain in the cookie, you should be skipping the domain which would mean the cookie would only be sent for the current domain (At least in modern browsers, IE does not follow this specification). If a domain is specified in the cookie it means that the cookie would also be used for the subdomains.
As mentioned in RFC 6265 - section 4.1.2.3:
If the server omits the Domain attribute, the user agent will return
the cookie only to the origin server.
Hence your cookie setting function should be like the following:
function setCookie(cname, cvalue, exdays) {
// Domain should not be set unless cookie needs to be accessed by subdomains
// var domain = window.location.hostname;
if (exdays > 7) exdays = 7; // max in Safari
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var name = cname + '=' + cvalue + '; ';
var expy = 'expires=' + d.toUTCString(); + '; ';
// Domain should not be set unless cookie needs to be accessed by subdomains
// var domn = '; domain=' + domain + '; ';
var path = 'path=/; ';
var secu = 'samesite=lax; secure;';
var complete = name + expy + path + secu;
document.cookie = complete;
}
As a temporary fix, I added some code to my setCookie function:
var domain = window.location.hostname;
deleteParentCookieIfNecessary(name, domain);
deleteParentCookieIfNecessary contains:
function deleteParentCookieIfNecessary(name, domain){
var parts = domain.split('.');
if (parts.length > 2){ // on subdomain
var domain = parts.slice(-2).join('.');
document.cookie = cname + '=;domain=.' + domain + ';path=/;max-age=0';
}
}
The result is that when the cookie is set, if the url is a subdomain then the parent-domain's cookie of the same name will be automatically deleted.

JavaScript redirect back to refer page

I am trying to make a button OR direct redirect which redirect user to page where he come from.
For example: If someone access my website from bbc post and register. Upon register success page, There should be a button or redirect function which take user back to bbc post or whereever he comes from.
I tried following cookie method but not worked also read some posts on stackoverlow but still no luck!
function setCookie(name,val,days) {
// DATE OBJECT
var date = new Date();
// NUMBER OF MILLISECONDS IN A DAY
var milliseconds = 86400000;
// MULTIPLY, THEN ADD TO CURRENT TIME
date.setTime(date.getTime() + (days * milliseconds));
// SET EXPIRATION VARIABLE
var expires = '; expires=' + date.toGMTString();
// CONCATENATE TO CREATE COOKIE
document.cookie = name + '=' + val + expires + '; path=/';
}
window.onload = function(){
if(document.referrer != ''){
// DESTROY ANY PREVIOUS DUPLICATE COOKIE
setCookie('referrer','',-1);
// CREATE COOKIE ON REGISTRATION PAGE
setCookie('referrer',document.referrer,1);
}
}
Can someone give any solution for this?
You can use the following and it should be useable in used even if the tab is opened in a new window.
if(document.referrer != ''){
// DESTROY ANY PREVIOUS DUPLICATE COOKIE
setCookie('referrer','',-1);
// CREATE COOKIE ON REGISTRATION PAGE
setCookie('referrer',document.referrer,1);
document.location.replace(document.referrer);
//replaces current url with new one eg. the (current) url is removed from history
//or
document.location.href = document.referrer;
//(current) url is in history/can use back button to go to previous page
}

create a cookie with javascript in greasemonkey

i'm trying to create a cookie with greasemonkey in order to stop a window from popping up (after the windows pops up a cookie is created the the window won't popup to many times...
this is the code
function setCookie(c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ?
"" :
";expires="+exdate.toUTCString());
}
var cookie_names = [
'showDrushimPopUnderUserClick',
'showDrushimPopUnder308'
];
for (var i in cookie_names) {
setCookie(cookie_names[i], 1, 0);
}
but no cookie is been created....
If you set a cookie that has an expires value equal to, or older than, the current system clock, it actually deletes the named cookie instead (Unless the path or domain are different, or it is a "secure" cookie -- none of which apply here).
This:
setCookie(cookie_names[i], 1, 0);
Causes that function to set a cookie with an instant expiration value, effectively deleting any cookie with that name.
To actually set a new cookie, use:
setCookie(cookie_names[i], 1, null);
which will cause your code to set a session cookie -- which is probably what you want.
Or use:
setCookie(cookie_names[i], 1, 1);
To set a cookie that expires in a day.

Issue with cookie, cookie is lost after closing browser

I've created a cookie like below and can retrieve all font_size, back_color and font_name. But once I close the browser the cookie is lost. From what I know is if we get expiry date wrong cookie can be lost but I've tested the date, expireGMT and is fine. Have I done anything wrong in the code below? Do I need to include path as well?
document.cookie = "font_size=14";
document.cookie = "back_color=Gray";
document.cookie = "font_name=Georgia";
document.cookie = "expires=" + expireGMT;
Each individual write to document.cookie is the setting of a cookie, and any options (including that cookie's expiration date) must be set on that write. You need to include the expiring time on every cookie assignment:
document.cookie = "font_size=14; expires=" + expireGMT;
document.cookie = "back_color=Gray; expires=" + expireGMT;
document.cookie = "font_name=Georgia; expires=" + expireGMT;
without that, each cookie will be created as session cookies and expire when the browser's closed.

A question about window.open and cookie

Say I have two apps, www.test.com and sub.test.com, now in sub.test.com, I create a window to load www.test.com with codes like :
window.open('www.test.com');
So the window just popup and load www.test.com successfully.
Then I set a cookie in sub.test.com, say "uname=wong2;domain=.test.com", I've learned that with set to domain=.test.com, all sites with domain test.com(such as www.test.com, aaa.test.com, test.com) can read the cookie.
But when I try to load the cookie from the window that just popup with www.test.com, it can't get it.
Then I found that if I don't use window.open but directly open www.test.com in browser, it works.
So is there some restrictions on window.open and cookie?
just check how you set the cookie:
var domain = 'test.com';
var expires = (function(days){
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
return date.toUTCString();
})(5);
var name = 'myCookie';
var path = '/';
var value = 'foo';
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path='" + path + "'; domain=" + domain + ";";
That is called cross domain and you cant set cookie in one domain and try to access that in different domain. Browsers wont allow doing this.I think you can accomplish this using iframe or same origin policy or try using document.domain I am not sure what you want to do exactly.

Categories