The function call cookieExists('stylesheet') should detect the presence of a cookie, returning true if the cookie called 'stylesheet' is present and false if not.
function cookieExists(name) {
var ckArr = document.cookie.split(';');
for(i = 0; i < ckArr.length; i++)
if (ckArr[i].split('=')[0].trim() == name) return true;
else return false;
}
This function is designed to check through the names of all existing cookies, but I am using it on a page which will only ever have one cookie - and its name is 'stylesheet'. I am calling it on pageload to check if the cookie called 'stylesheet' exists. This cookie specifies the CSS file last used (users can choose either stylesheet): either stylesheet1.css or stylesheet2.css. If the cookie called 'stylesheet' exists, I want to use the stylesheet specified in the cookie to display the page.
Now, if there actually is no existing cookie called 'stylesheet', cookieExists('stylesheet') does return false. If I then add a cookie called 'stylesheet' to the page, cookieExists('stylesheet') returns true. So far, so good.
However, if I then close the browser tab - while there is the cookie called 'stylesheet' attached to the page - and then open the same page in a new tab, cookieExists('stylesheet') no longer detects the cookie and returns false! The cookie is still attached to the page - it has not expired at the end of the previous session.
To be clear, I'm calling cookieExists('stylesheet') on pageload with window.onload = findStylesheet;, where the function findStylesheet() calls cookieExists('stylesheet'):
function findStylesheet() {
let savedStylesheet = cookieExists('stylesheet');
if (savedStylesheet) {
let setStylesheet = Cookies.get('stylesheet');
let newStylesheet = document.getElementById("stylesheet");
newStylesheet.setAttribute('href', setStylesheet);
}
}
The function Cookies.get('stylesheet') is a js-cookie function.
I would be very grateful if someone could point out where I'm going wrong.