I'm working on setting cookies for a website and I've been having trouble getting it right. When I check DevTools on my browser (Chrome), I'm always getting messages about the SameSite attribute being unspecified. Would anyone be able to help out?
const dropCookie = true;
const cookieDays = 14;
const cookieName = "Compliance";
const cookieState = "on";
const banner = document.getElementById("cookie-banner");
const displayBanner = () => {
const main = document.getElementsByTagName("main")[0];
banner.style.display = "flex";
main.className += " cookie-banner";
createCookie(window.cookieName, window.cookieState, window.cookieDays);
}
const createCookie = (name, value, days) => {
let cookie = name + "=" + encodeURIComponent(value);
if (typeof days === "number") {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
}
if (window.dropCookie) {
cookie = `${name}=${value}; ${expires}; path=/; secure; samesite=none`
document.cookie = cookie;
}
}
function checkCookie(name) {
const nameEq = `${name}=`;
const cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let c = cookieArr[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);
}
window.onload = () => {
if (checkCookie(window.cookieName) != window.cookieState) {
displayBanner();
}
}
I found that there were several reference errors being thrown from my code. I had to correct the instances where I referenced variables as properties of window, and also fix the Unix to UTC time conversion in createCookie.
const dropCookie = true;
const cookieDays = 14;
const cookieName = "compliance";
const cookieState = "on";
const banner = document.getElementById("cookie-banner");
const displayBanner = () => {
const main = document.getElementsByTagName("main")[0];
banner.style.display = "flex";
main.className += " cookie-banner";
createCookie(cookieName, cookieState, cookieDays);
}
const closeBanner = () => {
banner.style.display = "none";
}
const createCookie = (name, value, days) => {
let cookie = name + "=" + encodeURIComponent(value);
if (typeof days === "number") {
let date = new Date();
let unixDate = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
date = new Date(unixDate);
const expires = "expires=" + date.toUTCString();
if (dropCookie) {
document.cookie = `${name}=${value}; ${expires}; path=/; secure; samesite=lax`
}
}
}
Lastly, I fixed the window.onload statement by saving the function to a variable windowInit, then calling it in window.onload.
const windowInit = () => {
if (checkCookie(cookieName) != cookieState) {
displayBanner();
}
}
window.onload = windowInit();
Related
I've been trying to use 2 cookies and I changed all the variables and it still won't work only one cookie will work and if I remove the code for the first cookie the second one will work and vise vira. Someone please help me get this going.
var setCookie = function (n, val) {
var exdays = 365;
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = n + "=" + val + "; " + expires;
};
var getCookie = function (n) {
var name = n + "=";
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 "";
};
document.onclick = function (e) {
if (e.target.className == 'btn') {
var favColor = e.target.style.background;
setCookie('color', favColor);
document.getElementsByClassName('body-separator4')[0].style.background = favColor;
console.log(favColor);
}
};
window.onload = function () {
var favColor = document.getElementsByClassName("body-separator4")[0].style.background
var color = getCookie('color');
if (color === '') {
document.getElementsByClassName('body-separator4')[0].style.background = favColor;
} else {
document.getElementsByClassName('body-separator4')[0].style.background = color;
}
};
document.onclick = function (y) {
if (y.target.className == 'cbtn') {
var favbgColor = y.target.style.background;
setCookie('bgcolor', favbgColor);
document.getElementsByClassName('body-separator')[0].style.background = favbgColor;
console.log(favbgColor);
}
};
window.onload = function () {
var favbgColor = document.getElementsByClassName("body-separator")[0].style.background
var bgcolor = getCookie('bgcolor');
if (bgcolor === '') {
document.getElementsByClassName('body-separator')[0].style.background = favbgColor;
} else {
document.getElementsByClassName('body-separator')[0].style.background = bgcolor;
}
};
does anyone have time to help me with a little problem? I did this function to check the license time but it doesn't really work, does anyone have any idea?
https://cdn.discordapp.com/attachments/953617052202074132/954398145868083291/unknown.png
https://cdn.discordapp.com/attachments/953617052202074132/954398654217723914/unknown.png
exilied_client.on('message', async message => {
if (message.content.startsWith(`${prefix}time`)) {
automex = message.author;
if(message.guild == undefined) {
message.reply("Comenzile le poti da doar pe server-ul de discord");
return;
};
if(message.member.roles.cache.has(zedu_roldiscord)) {
const argomento = message.content.slice(prefix.length).split(/ +/g)
const comando = argomento.shift().toLowerCase();
var i = 1;
if(argomento[0])
{
if(message.member.roles.cache.has(zedu_roldiscord))
{
var verificaretimp = message.guild.member(message.mentions.users.first() || message.guild.members.fetch(argomento[1]))
} else {
message.delete()
message.reply(automex.username + " Ce gatu ma-tii vrei sa faci?")
return;
}
} else {
var verificaretimp = automex
}
const Verificare = `SELECT license, used, total_time FROM licenses WHERE userid = '${verificaretimp.id}';`
const autoreasd = querytxt => {
return new Promise((resolve, reject) => {
exilied_database.query(querytxt, (err, results, fields) => {
if (err) reject(err);
resolve([results, fields]);
});
});
};
const [results, fields] = await autoreasd(Verificare);
const Mappa1 = results.map(results => `${(results.used)}`);
const Mappa2 = results.map(results => `${(results.total_time)}`);
var TempoAttesa = parseInt (Mappa1, 10);
var TempoAttesa2 = parseInt (Mappa2, 10);
function ConvertireTimp(UNIX_timestamp){
var exilied_time = new Date(UNIX_timestamp * 1000);
var mesi = ['January','February','March','April','May','June','July','August','September','October','November','December'];
exilied_time.setDate(exilied_time.getDate() + TempoAttesa2);
var year = exilied_time.getFullYear();
var month = mesi[exilied_time.getMonth()];
var date = exilied_time.getDate();
var hour = exilied_time.getHours();
var min = exilied_time.getMinutes();
var sec = exilied_time.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ":"+ min;
return time;
}
message.delete()
var convertireatimp = ConvertireTimp(TempoAttesa2)
var expirelicense = automex.send("**__Your License Expired On__**: \n" + "" + convertireatimp + " \n If Not See Date Your Key Is Expired")
} else {
automex.send("**You Dont Have A License Key**")
}
}
});```
I am trying to access my API with a loop as this is one of my requirements. The code i have written is below.
currentWeekStartDate = (new Date(requestStartDate));
currentWeekEndDate = (new Date(requestEndDate));
let currentWeekStartDateNew = (new Date(requestStartDate));
let currentWeekEndDateNew = (new Date(requestEndDate));
console.log("testing ZONE");
/*test zone */
let outerEventArray = [];
while (currentWeekStartDateNew.getDate() !==currentWeekEndDateNew.getDate()){
console.log(currentWeekStartDateNew);
let startTIme = new Date(currentWeekStartDateNew);
let endTime = new Date(currentWeekEndDateNew);
startTIme.setHours(startHour,startMinute,0,0);
endTime.setHours(endHour,endMinute,0,0)
while(startTIme.getHours() !== endTime.getHours()){
let newStartTime = new Date(startTIme);
newStartTime.setHours(startTIme.getHours() + 1);
let firstTimeArg = startTIme.toISOString().replace("Z", "0000");
let secondTimeArg = newStartTime.toISOString().replace("Z", "0000");
let returnVal = getEventArray(access_token, firstTimeArg,secondTimeArg).then(res => {
return res;
});
if(returnVal !== null){
console.log("returnVal");
console.log(returnVal);
outerEventArray.push(returnVal);
console.log("returnVal");
}
/*
function
*/
startTIme = new Date(newStartTime);
}
currentWeekStartDateNew.setDate(currentWeekStartDateNew.getDate() + 1);
}
console.log("outerEventArray");
console.log(outerEventArray);
console.log("outerEventArray");
and my function for the API call is
getEventArray = async(access_token, startArguement,endArguement) => {
let eventVal;
let urlVal = "https://graph.microsoft.com/v1.0/users/" + user + "/calendarview?startdatetime=" + startArguement + "&enddatetime=" + endArguement + "";
request.get({
url: urlVal,
headers: {
"Authorization": "Bearer " + access_token
}
}, function (err, response, body) {
let bodyJSON = JSON.parse(body);
eventVal = bodyJSON.value;
if(eventVal == null){
console.log("eventVal is null");
}
else{
let eventArray = [];
for (let valueVal of Object.values(eventVal)) {
let eventStartTime = valueVal.start.dateTime;
let eventEndTime = valueVal.end.dateTime;
if (!((eventStartTime[eventStartTime.length - 1] === 'Z') || (eventStartTime[eventStartTime.length - 1] === 'z'))) {
eventStartTime = eventStartTime + "Z";
}
if (!((eventEndTime[eventEndTime.length - 1] === 'Z') || (eventEndTime[eventEndTime.length - 1]) === 'z')) {
eventEndTime = eventEndTime + "z"
}
eventArray.push({ start: new Date(eventStartTime).toLocaleString(), end: new Date(eventEndTime).toLocaleString() });
}
console.log(eventArray);
return eventArray;
}
});
}
However i am not able to get the outerEventArray value outside. My requirement is to access is outside with all the data populated. Is there any way this is possible?
The format change button when clicked gives both 24hrs and 12hrs format at a duration of 1 second. This may be due to something logical error in my code which i cannot figure out.
const clock = document.querySelector('.time');
const date_data = document.querySelector('.date');
const day_display = document.querySelector('.day');
const format = document.querySelector('.format');
const tick_24 = () => {
const now = new Date();
const h = now.getHours();
const m = now.getMinutes();
const s = now.getSeconds();
const html = `
<span>${h}</span> :
<span>${m}</span> :
<span>${s}</span>
`;
clock.innerHTML = html;
}
const tick_12 = () => {
const now = new Date();
const h = 30;
const m = now.getMinutes();
const s = now.getSeconds();
let hour;
if (h > 12) {
hour = h - 12;
} else {
hour = h;
}
const html = `
<span>${hour}</span> :
<span>${m}</span> :
<span>${s}</span>
`;
clock.innerHTML = html;
}
const day_disp = () => {
const now2 = new Date();
const day = now2.getDay();
let real_day = "";
if (day === 0) {
real_day = "Sun";
} else if (day === 1) {
real_day = "Mon";
} else if (day === 2) {
real_day = "Tue";
} else if (day === 3) {
real_day = "Wed";
} else if (day === 4) {
real_day = "Thu";
} else if (day === 5) {
real_day = "Fri";
} else {
real_day = "Sat";
}
const html = `${real_day}`;
day_display.innerHTML = html;
}
const date_dis = () => {
const now1 = new Date();
const date_log = now1.getDate();
const month = now1.getMonth();
const year = now1.getFullYear();
const html1 = `
<span>${date_log}</span> :
<span>${month+1}</span> :
<span>${year}</span>
`;
date_data.innerHTML = html1;
}
// const timer = () => setInterval(tick_12, 1000);
// timer();
let check = true;
const funct = () => {
const timer1 = () => setInterval(tick_24, 1000);
const timer2 = () => setInterval(tick_12, 1000);
if (check === true) {
timer1();
clearInterval(timer2);
check = false;
} else {
timer2();
clearInterval(timer1);
check = true;
}
}
format.addEventListener('click',() => {
funct();
})
const func = () => {
date_dis();
day_disp();
}
setInterval(func, 1000);
The expected results is that it must show 24hrs-format on one click and 12hrs-format on the other click and it must switch but it isn't working!
I have this code:
var CookieHelper = function () {
return {
GetCookie : function (cookieName) {
var cookieNameRequest = cookieName + "=";
var cookiesCollection = document.cookie.split(";");
for (var i = 0; i < cookiesCollection.length; i++) {
var cookieValuePair = cookiesCollection[i];
while (cookieValuePair.charAt(0) == " ") cookieValuePair = cookieValuePair.substring(1, cookieValuePair.length);
if (cookieValuePair.indexOf(cookieNameRequest) == 0)
return cookieValuePair.substring(cookieNameRequest.length, cookieValuePair.length);
}
return null;
},
DeleteCookie : function (cookieName) {
CookieHelper.SetCookie(cookieName, "", -1);
},
SetCookie : function (cookieName, cookieValue, cookieExpirationDays) {
var tmpDate = new Date;
if (cookieExpirationDays) {
tmpDate.setTime(tmpDate.getTime() + cookieExpirationDays * 24 * 60 * 60 * 1000);
var expires = "; expires=" + tmpDate.toGMTString();
} else {
// if cookieExpirationDays isn't set cookie will expire at the end of the day
var expirationTime = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate(), 23, 59, 59);
var expires = "; expires=" + expirationTime.toGMTString();
}
document.cookie = cookieName + "=" + cookieValue + expires + "; path=/;" + (location.protocol === "https:" ? "secure=true" : "");
}
};
}();
and I need to write unit tests for GetCookie.
I tried with:
QUnit.module('Cookie Helper Tests');
QUnit.test('GetCookie - returns no cookie', function(assert) {
var stub = sinon.spy(CookieHelper, 'GetCookie');
var cookieName = 'testCookieName';
var cookieValue = CookieHelper.GetCookie(cookieName);
assert.ok(cookieValue == null, 'returns no cookie');
});
I need to mock/stub document.cookie but I am completely new with Sinon and QUnit.
Can someone give me explanation what I did wrong?
Thanks in advance!
Srdjan
Well actually you can't mock properties with Sinon and more over you cannot mock the document.cookies property as it's immutable. What you can do though, is to use a fake double object that mimics the behavior of the original object, as described here.
For example, if you were running the same test outside of the browser (e.g. in NodeJS) you would do something like that
const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');
chai.use(SinonChai);
chai.should();
context('test', function() {
it('should pass',
(done) => {
var cookieName = 'testCookieName';
document = {
cookie: cookieName + '=123'
};
var cookieValue = CookieHelper.GetCookie(cookieName);
console.log(cookieValue);
done();
});
});
in order to introduce a document object to the context and mimic it's cookies attribute by returning a fixed result.
Now, there is a workaround for the browser which involves redefining the getter and setter of 'document.cookie' as described here:
(function (document) {
var cookies = {};
document.__defineGetter__('cookie', function () {
var output = [];
for (var cookieName in cookies) {
output.push(cookieName + '=' + cookies[cookieName]);
}
return output.join(';');
});
document.__defineSetter__('cookie', function (s) {
var indexOfSeparator = s.indexOf('=');
var key = s.substr(0, indexOfSeparator);
var value = s.substring(indexOfSeparator + 1);
cookies[key] = value;
return key + '=' + value;
});
document.clearCookies = function () {
cookies = {};
};
})(document);