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.
Related
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.
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
Using IE11, I can display the content of all cookies, write out a cookie, find it, and delete it using JavaScript, even though I have my Privacy set to "Block All Cookies". (And actually, no matter what version I set my IE emulation to, the document.cookie still works.) It works as it should on Chrome with cookies disabled - i.e. document.cookie returns empty/nothing when I try to reference it in the same JavaScript.
I'm trying to detect whether the user has cookies turned off in their IE. (Old ASP app that requires IE with cookies. No JQuery. No Modernizr.) To do that, I'm attempting to write out a cookie, find it, and then delete it. That either works or it doesn't - which should tell me whether cookies are turned ON or OFF. Any ideas? I thought this was the safest way to detect a user's IE cookie setting.
My code:
<script language=javascript>
cookiesON = false;
if ("cookie" in document ) {
alert("1. document.cookie (before add): " + document.cookie);
var dateNow = new Date();
document.cookie = "testcookie=" + new Date()
alert("2. document.cookie (after add): " + document.cookie);
if (document.cookie.indexOf("testcookie=") > -1) {
cookiesON = true;
} else {
cookiesON = false;
}
// delete cookie: set cookie to expire 2 minutes ago
document.cookie="testcookie=xx; expires=" + (new Date(dateNow.getTime() - 2*60000).toGMTString());
alert("3. document.cookie (after delete): " + document.cookie);
}
On IE:
All 3 alerts show values for document.cookie, no matter whether cookies are turned on or off. You can see the testcookie being added and deleted back off.
On Chrome:
All 3 alerts show blank for document.cookie when cookies are off. Works as described for IE when cookies are turned on.
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
}
I need (for practice) to set a cookie via bookmarklet in website X, and read him with another bookmarklet from website Y.
For example, set a cookie named "user" with value of "Guy" in Google, and read this from YouTube.
I managed to set the cookie, but can't think of any idea how to read him from website b.
Thanks!
You need two bookmarklets, a getter and a setter.
You go to site X and use the getter bookmarklet to read the cookie and let the user copy it to his clipboard.
Then you go to site Y and use the setter. The setter will prompt the user for the bookmarklet and the user will then paste it into the prompt. The code will then set the cookie accordingly.
You can of course combine these two bookmarklets into a single getter/setter. The prompt will contain the current cookie for the page. The user can then choose to either copy the cookie and cancel (using it as a getter) or choose to to alter the cookie and click "OK" (using it as a setter).
I was looking for a way to share cookies of a specific website with a friend (reading them in my browser via bookmarklet and my friend setting them on his browser also via bookmarklet). Not quite what you asked for, but searching brought me here. This is my approach:
First there is a bookmarklet for exporting cookies. It will remove unnecessary white-spaces and encode your data in a base64 string for safe transport:
javascript:(
function(){
prompt("GET cookies encoded in base64", btoa(document.cookie.replace(/\s/ig, "")));
}
)
();
Then there is a second bookmarklet for importing all cookies encoded in the string. You can also set an optional lifetime here (thanks to https://www.quirksmode.org/js/cookies.html):
javascript:(
function(){
var inputstring = prompt("SET cookies decoded from base64");
var inputclean = atob(inputstring).replace(/\s/ig, "");
if (confirm("These cookies will be imported:\n\n" + inputclean.replace(/;/ig, "; "))) {
var days = prompt("Cookie lifetime in full days", "365");
var cookiearray = inputclean.split(";");
cookiearray.forEach(function(entry) {
var expires = "";
var split = entry.split("=");
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = split[0] + "=" + (split[1] || "") + expires + "; path=/";
});
}
}
)
();
Do not forget you have to run those on a specific website or tab. It does NOT export the entire collection of the cookies your browser is storing.
According to this StackOverflow, how to get cookies from a different domain with php and javascript you can't get cookies from another domain UNLESS you have access to it, as it would be a huge security flaw.