I wrote a script in javascript to delete all cookies (except some included in a whitelist) within the current domain (using document.cookie). How can I make sure that it is working and indeed deleting the cookies?
I ran it in the browser by including it in an html file and then opening that file, but I don't understand how to test that it will delete cookies within the domain since when I open an html file it is not associated with a domain.
Here is my code:
//cookies we need
const whitelist = [
'example_cookie',
];
function removeUnnecessaryCookies() {
let decodedCookie = decodeURIComponent(document.cookie); //check for special characters
let allCookies = decodedCookie.split(';'); //make array of all cookies in domain
for (var i = 0; i < allCookies.length; i++) {
let cookie = allCookies[i];
if (!whitelist.includes(cookie)) {
deleteCookie(cookie);
}
}
}
/* helper function to delete cookies */
function setCookie(cookieName, cookieValue, cookieExpiry) {
let date = new Date();
date.setTime(date.getTime() + (cookieExpiry*24*60*60*1000));
let expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
function deleteCookie(cookieName) {
setCookie(cookieName, '', -100);
}
removeUnnecessaryCookies();
Write a getCookie method and test for that. Here is an example:
function setCookie(name, value, days) {
var expiry = new Date()
expiry.setTime(expiry.getTime() + (days * 24 * 60 * 60 * 1000))
var expires = 'expires=' + expiry.toUTCString()
document.cookie = name + '=' + value + ';' + expires + ';' + 'path=/'
}
function getCookie(name) {
var name = name + '='
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 false
}
// set cookie
setCookie('mycookie', '1', 365);
// get cookie
getCookie('mycookie');
getCookie('joe'); // returns false
Your best bet would be to spin up a localhost webserver (something like WAMP or MAMP or Mac should do the trick) and drop a cookie. Look at the domain in your browser and copy that.
Related
I'm definitely new to Javascript, but I need to implement a tag within GTM to update 2 cookie values to 6 months for any unique user after the are loaded on the page.
I have the following script to alter the expiration date:
<script>
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
var date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
console.log("expires: " + expires);
var cookieName = "CookieA";
var OABCcookieName = "CookieB";
function updateCookieExpiration() {
var cookie = getCookie(cookieName);
document.cookie = cookieName + "=" + cookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
var OABCcookie = getCookie(OABCcookieName);
document.cookie = OABCcookieName + "=" + OABCcookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
}
</script>
My question is, if I add the following script, update 365 to 180, and call the updateCookieExpiration() function - won't the function be called on every page and cause the cookie expiration to always reset to 6 months?
If so, is there additional logic that I need to add to make sure the cookie expiration hasn't already been reset for a unique visitor, to avoid the scenario described?
Any help troubleshooting would be great and very appreciated!
You could add a condition check if the Cookie name already exist:
// You may prefer using max-age here
const sixMonthMaxAge = 60 * 60 * 24 * 180;
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = getCookie(cookieName);
// If cookie doesn't exist
if(!cookie) {
document.cookie = cookieName + "=" + cookie + ";" + "max-age=" sixMonthMaxAge + ";"
}
}
Using js-cookie library
Using library that abstract Cookie management can be a good idea, even more if you have to manager multiple cookies.
import Cookies from 'js-cookie'
const sixMonthMaxAge = 180; // You can provide the max-age in days
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = Cookies.get(cookieName);
if(!cookie) {
Cookie.set(cookieName, 'your_value', { expires: sixMonthMaxAge })
}
}
Cookies.set('foo', 'bar')
I want to create a button on my webpage, which when clicked, sets a cookie with a specified value. The cookie should be valid for the entire domain, all its directories and sub-domains.
The code I'm using now is this:
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "name1" + cvalue + "value1" + expires + ";path=/";
}
Then, once the cookie and its value is set, I want that button to get deleted from the page. Also, next time the page loads, I want to check if the cookie and the value exists and if not, show the button or else, delete the button.
The button in context has an id: delete
I'm using this code to check for cookie and its value:
function getCookie(name1)
{
var name = name1 + "value1";
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 "";
}
I've found these codes from here: https://www.w3schools.com/js/js_cookies.asp
I'm going to use this code to delete the element if the cookie and its value is present:
function removeElement(elementId)
{
var element = document.getElementById(delete);
element.parentNode.removeChild(element);
}
I've taken this code from here: https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript
I don't know how to link those 2 fuctions to carry out the required action.
Here is a working solution for you. Take a look at the comments inside the Code.
Are u new to JS? in this case you should take a look at codecademy. Its for free and you will learn the basics very fast.
Note that SO does not allow you to check or set cookies. For that reason the runable code below will cause an error. Here is a working fiddle.
if (getCookie('myCookie')) removeElement('myButton'); // remove if cookie is set
if (document.getElementById('myButton')) document.getElementById('myButton').onclick = function() { // bind function to clickevent
setCookie('myCookie', 'myValue', 1); // set cookie
removeElement('myButton'); // remove button
}
function setCookie(cname, cvalue, exdays) { // your setCookie Funktion
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + '=' + cvalue + '; '+ expires + ";path=/"; // reset to w3schools solution
}
function getCookie(name) { // your getCookie Funktion
// removed 'var name = ...' because you wont find your cookie if you changing the name here
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 "";
}
function removeElement(elementId) { // your removeElement Function
var element = document.getElementById(elementId); // variable delete was undefined, if your buttons id was delete you had to write it in ''
element.parentNode.removeChild(element);
}
<button type="button" id="myButton">
click me
</button>
Going by your requirements you just want to delete a specific button if the cookie is present.
In this case you will need to do 2 things.
Call the getCookie and based on the return value call the removeElement at the end of the setCookie method.
Note: I am assuming your setCookie method is synchronous.
Load the button by default and do the same as Step 1 once the page is loaded.
To summarize, your mrthods should look like this:
setCookie method:
function setCookie(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "name1" + cvalue + "value1" + expires + ";path=/";
if(getCookie(cname)) removeElement('delete');
}
After Loading the document:
document.onload = ()=>{
if(getCookie(cname)) removeElement('delete');
}
I'm trying to define a version for my website so it can reload the resources if the versions don't match. The problem is that when I fetch the cookie, the cookie value is not returned. The result of this is that the website is in a constant state of reloading.
I made sure that the cookie was there and I tried using my functions in the console and setting the cookie manually.
Webpage:
var version = '1.0.0';
var cVersion = version == getCookie("version");
if(!cVersion) {
setCookie("version", version, 1000);
window.location.reload(true);
}
Cookies Script:
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 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 "";
}
The website should reload and update the version number if they are different and do nothing if they are the same.
Link to code to test: https://jsbin.com/modocelume/edit?js,console
One of my cookies are always coming up null. The rest read fine. In the actual application, it's meant to read URL parameters. In that scenario, I can actually change which one is null, but it's always at least one!
I can see the cookie is set in the developer tools, it's not HTTP Only, and the expiration is fine.
Anyone have any experience with this?
var urlParams = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content'
];
function createCookie(name, value, days, domain) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = '; expires=' + date.toGMTString();
} else {
var expires = '';
}
if (domain) {
var domain = '; domain=' + domain;
}
document.cookie = name + '=' + value + expires + domain + '; path=/';
}
function readCookie(name) {
var name = name + '=',
fields = document.cookie.split(';');
for(var i=0; i < fields.length; i++) {
var field = fields[i];
while (field.charAt(0)==' ') {
field = field.substring(1, field.length);
if (field.indexOf(name) == 0) {
return field.substring(name.length, field.length);
}
}
}
return null;
}
urlParams.forEach(function(param) {
createCookie(param, param, 365, '');
});
urlParams.forEach(function(param) {
console.log(readCookie(param));
});
I expect the output for readCookie('utm_source') to be utm_source, but the output is null.
Thanks for your help!
For some reason, your utm_source field name did not have an empty space in front of it, so your while (field.charAt(0) === ' ') didn't fire for it. I changed it to below code and it seems to be working fine now:
function readCookie(name) {
var name = name + '=',
fields = document.cookie.split(';');
for(var i=0; i < fields.length; i++) {
var field = fields[i].trim();
if (field.indexOf(name) == 0) {
return field.substring(name.length, field.length);
}
}
return null;
}
I'm trying to set a cookie using javascript so it expires when the browser is closed.
I have the following function to do that:
function createCookie(value,days) {
var name = "name";
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var cookie = name + "=" + value + expires + "; path=/";
document.cookie = cookie;
}
I tried many ways found here and there on the web like setting the date to "", setting it to yesterday (in that case the cookie is not even added) and omitting "expires" completly. I tried on Firefox and Chrome checking that every process was stopped before opening again, but the cookie is alway there.
What am I missing?
I am using this function for my self. It will work for you i gess :)
function createCookie(name, value, expiresInX_days, path) {
var a = new Date;
var expires = expiresInX_days || 1;
a.setTime(Date.now() + (1000 * 60 * 60 * 24 * expires));
var pt = path ? " ; path=" + path + ";" : ";";
return (document.cookie = name + "=" + value + ";" + "expires=" + a.toUTCString() + pt) ? !0 : !1;
}
If you want to delete your cookie, you can use this:
function rmCookie(cookieName){
var a = new Date;
a.setTime(0);
return (document.cookie = cookieName + "=;" + a.toUTCString()) ? !0 : !1;
}
If you want get your cookie clean,
function getMyFuckingCookie(cookieName){
var a = document.cookie.replace(/; /g, ";").split(";"),
b = a.length,
c = {},
nm = cookieName || !1;
while (b--) {
var d = a[b].split(/=(.+)/);
c[d[0]] = d[1];
}
return (nm) ? c[nm] : c;
}