Create and Delete cookies for external websites on their subdomain - javascript

Set Cookie function in Jquery
function setCookie(cookieName, cookieValue, cookieExpireDays) {
var d = new Date();
d.setTime(d.getTime() + (cookieExpireDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";" + "path=/";
}
Delete function in Jquery
function deleteCookie(name) {
var domain = location.hostname,
path = '/'; // root path
document.cookie = [
name, '=',
'; expires=' + new Date(0).toUTCString(),
'; path=' + path,
'; domain=' + domain
].join('');
}
This works fine for local links, but when I try to use it on external websites. I can get my document.cookie but deleteCookie function does not delete the cookie. Any ideas?
*Please remember, I am just running these scripts from console of Google Chrome

I might be misunderstanding something in your question, but here's how I handled the getting, setting, and deleting of a cookie I set.
fiddle: https://jsfiddle.net/hmvyu3L6/
<button class='set'>set</button>
<button class='get'>get</button>
<button class='delete'>delete</button>
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;
}
function getCookie(cname) {
var name = cname + '=',
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 deleteCookie( name ) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var value = 'hey there';
$('.set').on('click', function() {
setCookie('testCookie', value, 360);
});
$('.get').on('click', function() {
console.log(getCookie('testCookie'));
});
$('.delete').on('click', function() {
deleteCookie('testCookie');
});

If the cookies are HttpOnly, you will not be able to delete them using javascript or jquery.
Make sure your domain and path match exactly. If they are different (e.g. .subdomain.domain.com instead of .domain.com, or /path instead of /) then the script will not affect the cookies.

Alright, I am answering my own question because I changed few things and it works now.
var domain = location.hostname
function setCookie(cookiename, cookievalue, expiredays, domain) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expiredays=" + date.toGMTString();
document.cookie = cookiename+ "=" + cookievalue+ expires + "; domain=" + domain + "; path=/";
}
function deleteCookie(cookiename, domain) {
setCookie(cookiename, "", -1, domain);
}
deleteCookie("Cookie_Name",domain)

Related

Add a value to a cookie with expiration data?

How can I add a cookie which expires in 2 months to 'test#gmail.com' from the following code
<div id="home">
<div class="name" my-data="123">Email: test#gmail.com</div>
</div>
I think the code for the actual time should be as follows but I do not know how to add the value to it:
function myemail () {
var expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString
Assuming you have privileges to add an ID to your div, the following code works fine
<body>
<div id="home">
<div class="name" my-data="123" id="email-div">Email: test#gmail.com</div>
<button onclick="myemail()">Set it</button>
</div>
<script>
function myemail() {
var expiryDate = new Date();
var email = document.getElementById("email-div").textContent.split("Email:")[1]
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = 'emailCookie=' + email + ';expires=' + expiryDate.toGMTString() + ';path=/';
}
</script>
</body
Well I have used a button to trigger the action. You can do the same in any event.
toGMTString is a function, you need to call.
Replace expiryDate.toGMTString to expiryDate.toGMTString()
const Cookie = {
get: function (name) {
const nameEq = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let 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;
},
set: function (name, value, hours) {
const expires = "";
if (hours) {
let date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
const expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
};
You can change hours to whatever and of course
this one date.setTime(date.getTime() + (hours * 60 * 60 * 1000)); to the corresponding formula
Usage`
Set: Cookie.set('myemail', 'test#gmail.com', 1460) // 1460 is 2 months in hours
Get: Cookie.get('myemail')
const email = document.getElementsByClassName('name')[0].textContent.split(' ')[1]; Cookie.set('myemail', email, 1460);

JavaScript cookie that expires after one day

I'm attempting to learn to set a JS cookie that expires after one day, but our client is reporting intermittent results with this. Am I missing something? Is there a better way to go about doing this?
Honestly, I'd also be open to setting a session cookie to alleviate the problem, but I figured I'd see if someone spotted an error in the way we're doing this here first.
Thank you!
(function($){
checkCookie();
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 noShowWelcome = getCookie("sameSessionSKF");
if (!noShowWelcome) {
$('#home-alert').modal({
fadeDuration: 500
});
setCookie('sameSessionSKF', true, 1); // sets to expire after 1 day
}
}
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Instead of expires you can specify Max-Age, which is the number of seconds until the cookie expires.
const maxAge = 86400
document.cookie = cname + "=" + cvalue + ";Max-Age=" + maxAge + ";path=/";

How to load url along with saved Cookies in Javascript?

I would like to load my url using javascript, Where my url is required authorization token. The token already saved in cookies with the following code.
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
</script>
And able to get saved token from cookies successfully but not able to apply for my url load which is required authentication token.
Can any one suggest me a way to load url with authorization token from cookies.
NOTE: I can not pass the authorization token in url as parameter.
Here is my url loading code:
<script>
function newDoc() {
window.location.assign("https://mydomine.com/Viewer?type=xyz")
}
</script>
If you are trying to set the cookie for a different domain, then you'll need to add the domain information to the cookie.
function setCookie(cname, cvalue, exdays, domain) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
var cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
// Add the domain, if specified.
if (domain) {
cookie += `;domain={domain}`
}
document.cookie = cookie;
}

Can't able to set expiry date in cookie using javascript?

I am using following function
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;
}
setCookie("userName","vimalraj.s",1);
It create cookies in a "session " not with a 24 hours expiry time .
how to fix this ?
UPDATE :
The above code works fine in my colleague's computer Firefox(27.0.1)
and it doesn't for me same Firefox version
I even tried "max-age" instead of "expires"
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
Nothing worked ...
Taken from quirksmode.org.
function createCookie(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) {
createCookie(name,"",-1);
}
Here is for one day
createCookie('ppkcookie','testcookie',1)
I suggest you to create a new cookie with same cookie name.
now you can set the new expire.
This will over ride the existing cookie since both are of same name.
Now the new cookie will have the new expires
old cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
new cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
I hope this will help

Getting value from a cookie

I have set a cookie using the following and it works well. I can see it in browser cookie(console).
But how can i get back the value from cookie ??
days = 1;
cookiename = 'uid';
cookieValue = result.pp.uid;
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 = cookiename + "=" + cookieValue + expires + "; path=/";
I have the following code , but i dont want to use the function.
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;
}
Ive no idea of how they are getting the value of cookie..
Is there a simple way like document.cookie ?
Try this library
https://github.com/carhartl/jquery-cookie
Also see this SO post
How do I set/unset cookie with jQuery?
Example from their docs
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

Categories