I would like to be able to check if a cookie (id) is set or not: if not set, then create it. If set, retrieve the value (= an array). How can I retrieve the array from the cookie?
I hear that I would have to use JSON, but I'm not sure how that would work with the following code?
function start(id){
if (document.cookie.indexOf('id') === -1 ) {
setCookie('id', id, 7);
}
else {
var playedID = [GET COOKIE ARRAY]
playedID.push(id);
setCookie('id',playedID);
}
}
Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.
getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp
// This won't run due to security policies on this site, but you can run it in the dev tools and see.
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 "";
}
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 getCookieArray(cname) {
var cookie = getCookie(cname);
return cookie ? JSON.parse(cookie) : [];
}
function pushToCookieArray(cname, cvalue, exdays) {
var cookieArray = getCookieArray(cname);
cookieArray.push(cvalue);
setCookie(cname, JSON.stringify(cookieArray), exdays);
}
function start(id) {
pushToCookieArray('id', id, 7);
console.log(getCookieArray('id'));
}
start(5);
start(6);
start(8);
First a cookie is not stored as an array but a string : if you type document.cookie in you console, you will get all the cookies from the website you are visiting, separated with a coma.
So as explained here : https://www.w3schools.com/js/js_cookies.asp,
you will have to create a custom function to access the cookie you need.
Then the value of you cookie is still a string, so as explained here if you want to save an array of ids, you have to use JSON.stringify to encode you array as a string : I want to store Javascript array as a Cookie
You can then create it or update its value :
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 "";
}
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";";
}
function start(id){
if (getCookie('id') === '' ) {
setCookie('id', JSON.stringify([+id]));
}
else {
let ids = JSON.parse(getCookie('id'))
console.log(ids)
ids.push(+id);
setCookie('id', JSON.stringify(ids));
}
}
function sendID(id) {
console.log(document.getElementById("user-id").value)
start(id);
alert(getCookie("id"))
}
Here is a working example : https://codepen.io/adrientiburce/pen/ExVbYWy?editors=1010
Related
I have a script that draws a random picture after pressing the button.
var imagesArray = ["slonce.gif", "gwiazda.gif", "kochankowie.gif", "wieza.gif"];
function displayImage(){
var num = Math.floor(Math.random() * 4); // 0...6
document.picture.src = imagesArray[num];
}
I want the picture to be remembered for the whole day on the computer or IP that randomized it.
I read about local storage and cookies but I have no idea how I can set the lifetime of this choice.
I created something this and it works
function createCookie(cookieName,cookieValue)
{
var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function getCookie(cookieName)
{
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
function checkCookie()
{
var number = getCookie("randomPicture");
if (number!=""){
document.picture.src = imagesArray[number];
}
else
{
var num = Math.floor(Math.random() * 4); // 0...3
document.picture.src = imagesArray[num];
if (num!=null)
{
createCookie("randomPicture", num);
}
}
}
called with the function checkCookie()
One simple option that you have, would be to store a cookie on the computer which expires after one day. Then, at the time the page is loaded you can use JavaScript to check if the cookie is there.
If it is, then you can show the button, otherwise show the picture.
W3Schools covers how to store a cookie and provides a function:
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=/";
}
They also have written a function get a cookie:
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 "";
}
This getCookie function code is from https://www.w3schools.com/js/js_cookies.asp
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 part which I cannot understand easily is decodedCookie
var decodedCookie = decodeURIComponent(document.cookie);
I've already searched for articles about decodeURIComponent,
and It decodes the encodedURIComponent.
But since theres no encoded cookie, why decodeURIComponent(document.cookie) needed?
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=/";
}
This is the code of setcookie function from w3schools, and they didnt set the cookie withencodeURIComponent`.
So... why?
I need some detailed explanation! Thanks!
It is already mentioned in the tutorial:
Decode the cookie string, to handle cookies with special characters, e.g. '$'
But since we do not have '$' then you can remove it with no effect here.
Is there a way to have my page continuously monitor for a cookie in realtime with Javascript, and if the cookie ever is set then it will send an alert?
The part that I don't understand is how do you check for the cookie in realtime? For example, a user might click a checkbox, a cookie will get set, and then the page to "see" that the cookie is now set and trigger an alert, all in real-time without delay.
Here's an example (not written correctly) that kinda shows what I'm going for.
<div id="click" onclick="setcookie()"></div>
<script>
function checkcookie() {
if (cookie_exists)
alert('cookie exists')
}
</script>
The part that I don't understand is how do I get checkcookie() function to continuously be monitoring for the existence of the cookie I just set with my click?
You have to implement an interval timeout to continuously check for a cookie's value.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
// Method used for continuously monitoring a cookie
function monitorCookie(cookieName) {
setInterval(function() {
var cookieValue = getCookie(cookieName);
console.log('Yummy Cookie =' + cookieValue);
}, 500);// monitor cookie every 500 miliseconds.
}
$(document).ready(function() {
monitorCookie("YummyCookie");
});
The only way is to use
window.setInterval("CheckCookie()", 1000);
Which checks for cookie every second
Here are basic functions for writing and reading cookies:
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 null;
}
function checkCookie(cname) {
var cookie = getCookie(cname);
if (cookie != null) {
return true;
} else {
return false;
}
}
function remove_cookie(cname) {
document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;'
}
from w3schools.com/js/js_cookies.asp
I have been stuck on this problem for a couple hours now, and cant seem to get off of it. I have a html website where i'm giving a user a cookie called "schoolid" and it has the school's ID in it. If a user has a certain school ID, in this case "gms08",they will be redirected to another website. This is what i have so far in the cookie area.
I have a check cookie function checking to make sure the user has it, but i cant seem to get it to pick up on the fact that the user has the cookie and it is gms08.
i.stack.imgur.com/wQjnx.png
Pastebin: http://pastebin.com/Gfjc7iTG
<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=/";
}
</script>
<script>
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 "";
}
</script>
<script>
function checkCookie() {
var id = getCookie("schoolid");
if (id != "") {
alert("Welcome again ");
} else {
alert("user");
}
}
</script>
I have to create a JS cookie when a user click a button, this cookie will remember him after 10 minutes with another popup.
Example:
<button>Click me!</button>
and the button will hide when user click, after 10 minutes the button will show again:
<button>Click me!</button>
Script part:
function setCookieMsg(name) {
var d = new Date();
var time = d.setTime(d.getTime() + (600000));
document.cookie = name + "=" + time;
}
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) != -1) return c.substring(name.length, c.length);
}
return "";
}
function checkCookieMsg() {
var cookie = getCookie("name");
var d = new Date() - 600000;
if (cookie == "") {
setCookie("name", cookie);
}else if (d => cookie) {
$().getUnReadMessage();
}
}
What I've wrong?
You didn't mention the expires in cookie. The expires date should be UTC time string.
function setCookieMsg(name) {
var date = new Date();
date.setTime(date.getTime()+(600000));
var expires = "; expires="+date.toUTCString();
document.cookie = name + "=" + expires;
}