Sharing Cookie among browser tabs without refreshing tab in javascript - javascript

hi i am designing a real estate website and i have many ads in it i add an option to every of my ads and if user click on "add to favorites" that ad's id and url saves in a cookie and retrieve in "favorite page" thus user can review that certain ad every time he or she wants. each of my ads have a address like this localhost/viewmore.php?ID=a number
totally saving process in cookie works fine but recently i realized something. consider i visit one of my ads with this address localhost/viewmore.php?ID=10 and click on "add to favorite" then if i open another page with this address localhost/viewmore.php?ID=8 and then i read my cookie in "favorite page" i will see this result
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is perfectly true and it is what i expect.
the problem
now consider unlike the previous case i open both of ads and then click on "add to favorite" on first ad and then go to second ad (without any refreshing) and click on "add to favorite" on second ad this time if i read my cookie in "favorite page" i will see this result
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is not true i want two see both of ad's id and url in my cookie not just last one.
ps: i use push() method to add new object to cookie array i think i have to update it every time after click? any idea thanks
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
function isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
// this is the part i think i have to update every time without refreshing*******************************
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
if(isAlready()){
} else {
var fav = {'favoriteid':favID,'url':url};
faves.push(fav);
}
//*******************************************************************************************************
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
});

Your problem is that you are looking at variable faves, which is initialized at document load, but it isn't being updated as cookie changes.
The second page looks at the variable, sees no favorites from first page, because it doesn't actually look at cookie.
Then, it just resets the cookie with it's values.
Here is the full code, with added functionality from chat:
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = {
add: function (new_obj) {
var old_array = faves.get();
old_array.push(new_obj);
faves.create(old_array);
},
remove_index: function (index) {
var old_array = faves.get();
old_array.splice(index, 1);
faves.create(old_array);
},
remove_id: function (id) {
var old_array = faves.get();
var id_index = faves.get_id_index(id);
faves.remove_index(id_index);
},
create: function (arr) {
var stringified = JSON.stringify(arr);
createCookie('favespages', stringified);
},
get: function () {
return JSON.parse(readCookie('favespages')) || [];
},
get_id_index: function (id) {
var old_array = faves.get();
var id_index = -1;
$.each(old_array, function (index, val) {
if (val.id == id) {
id_index = index;
}
});
return id_index;
},
update_list: function () {
$("#appendfavs").empty();
$.each(faves.get(), function (index, value) {
var element = '<li class="' + index + '"><h4>' + value.id + '</h4> Open page ' +
'Remove me';
$('#appendfavs').append(element);
});
}
}
$(function () {
var url = window.location.href;
$(document.body).on('click', '#addTofav', function (e) {
var pageId = window.location.search.match(/ID=(\d+)/)[1];
if (faves.get_id_index(pageId) !== -1) {
faves.remove_id(pageId);
}
else {
faves.add({
id: pageId,
url: url
});
}
faves.update_list();
});
$(document.body).on('click', '.remove', function () {
var url = $(this).data('id');
faves.remove_id(url);
faves.update_list();
});
$(window).on('focus', function () {
faves.update_list();
});
faves.update_list();
});

Related

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

set cookie on page to show bootstrap popup once a day

I'm learning JavaScript and I see that this question has been asked many times, but I can't get this to work for me.
What I want to do is, show a bootstrap modal once a day.
What I have so far is:
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Now, if I change the last return true; to return false; my modal does not show up.
The way it is now I see the modal every time.
What am I doing wrong?
How can I fix this?
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Also when setting cookie,
use
setCookie('showed',new Date().toGMTString(),1);
because we are using the value of cookie, not the expire time of cookie to check. So the value must be a datestring

how to pass variable to next page with cookies

I am designing a real estate website. I have many ads in my website and thanks to my friend Arsh Singh I create a 'favorite' or 'save' button on each of the posts that will save the selected page title in a certain page based on cookies for user to review the post when ever he or she wants.
Now i want to send ad's id to the favorite page when user click on "add to favorites" thus based on id i can fetch that certain ad data from database .
can i do this? how? this is my current code and it can only send page title to the favorite page. any idea?
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src=favoritecookie.js></script>
</head>
<body>
Add me to fav
<ul id="appendfavs">
</ul>
<?php
error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php while($row = mysqli_fetch_array($result)):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
?>
<?php
echo"price";
echo"room";
echo"date";
?>
<?php endwhile;?>
</body>
</html>
//favoritecookie.js
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
function isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
if(isAlready()){
} else {
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
}
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
JSON in Cookie
You can use JSON to store the details (id, post name, etc) into a cookie by serialising the JSON:
jquery save json data object in cookie
However you should not store database table names in cookies for security's sake.
PHP cookies access
https://davidwalsh.name/php-cookies
I would use pure PHP... setcookie() to place a cookie, and read it back when needed using PHP $_COOKIE. Since there would be a need to store a lot of data, structured, related or not, I would then create an associative array, fill it accordingly and then use PHP serialize() it before save it in a cookie; unserialize() when reading:
Saving:
a) $data = array("ID"=>value, "otherdata"=>value...etc);
b) $dataPacked = serialize($data);
c) setcookie("cookieName", $dataPacked);
Reading:
a) $dataPacked = $_COOKIE["cookieName"];
b) $data = unserialize($dataPacked);
Then use $data array as needed. If I would need some Javascript with that data I would simply do:
<script>
var jsVar = "<?php echo $data['key'];?>";
Or go fancier with loops to write more vars from $data, etc.
Here is refactored code that works better (from SO answer):
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = {
add: function (new_obj) {
var old_array = faves.get();
old_array.push(new_obj);
faves.create(old_array);
},
remove_index: function (index) {
var old_array = faves.get();
old_array.splice(index, 1);
faves.create(old_array);
},
remove_id: function (id) {
var old_array = faves.get();
var id_index = faves.get_id_index(id);
faves.remove_index(id_index);
},
create: function (arr) {
var stringified = JSON.stringify(arr);
createCookie('favespages', stringified);
},
get: function () {
return JSON.parse(readCookie('favespages')) || [];
},
get_id_index: function (id) {
var old_array = faves.get();
var id_index = -1;
$.each(old_array, function (index, val) {
if (val.id == id) {
id_index = index;
}
});
return id_index;
},
update_list: function () {
$("#appendfavs").empty();
$.each(faves.get(), function (index, value) {
var element = '<li class="' + index + '"><h4>' + value.id + '</h4> Open page ' +
'Remove me';
$('#appendfavs').append(element);
});
}
}
$(function () {
var url = window.location.href;
$(document.body).on('click', '#addTofav', function (e) {
var pageId = window.location.search.match(/ID=(\d+)/)[1];
if (faves.get_id_index(pageId) !== -1) {
faves.remove_id(pageId);
}
else {
faves.add({
id: pageId,
url: url
});
}
faves.update_list();
});
$(document.body).on('click', '.remove', function () {
var url = $(this).data('id');
faves.remove_id(url);
faves.update_list();
});
$(window).on('focus', function () {
faves.update_list();
});
faves.update_list();
});
finally i got the answer. replace this javascript code instead of question javascript (favoritecookie.js) and you will see that it works like a charm.with this u code can save id in cookie and then retrieve it where ever u want
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
function isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
$(document.body).on('click','#addTofav',function(){
if(isAlready()){
} else {
var fav = {'favoriteid':favID,'url':url};
faves.push(fav);//The push() method adds new items (fav) to the end of an array (faves), and returns the new length.
}
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4> '+
'Remove me';
$('#appendfavs').append(element);
});
});
</script>

Weird behaviour with cookies and firefox

Edit: This only happens in firefox, it works fine in chrome.
Edit 2: Due to there apparently not being a solution to this (sessionid breaks when there are other cookies present) i've decided to use localstorage instead (it's also a much better approach)
I have an audio player on my website (website powered by django) and I want to store the current time, the source and the state (is it playing or not) in cookies. So when you refresh the page while music is playing, it'll continue where you left off. I have a timer set to update the cookie track_time every second. And it works, however:
When you try logging into the website a second time, while audio is playing, it won't let you. It says in my console that the login happened, but firefox doesn't seem to store the session. When I disable the script that is writing the cookies, it works again.
Here's proof:
http://puu.sh/nkqIX/23160ce67e.png
What in the world is happening here? I'm not recieving any errors, it just doesn't work.
Code:
This snippet here creates, reads, and deletes cookies.
/** Cookies **/
function createCookie(name, value, days) {
'use strict';
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);
}
In audio.js I have the following functions:
// Cookie? //
function audioCookie() {
'use strict';
var track, track_time, track_state;
track = readCookie('track');
track_time = readCookie('track_time');
track_state = readCookie('track_state');
if (track !== null) {
track = JSON.parse(track);
audioCurrent = new AudioTrack(track.src, track.artist, track.title, track.genre, track.type);
audioCurrent.setSrc();
if (track_state === '1') {
audioCurrent.play();
}
setTimeout(function () {
audioCurrent.time(track_time);
audioSetProperties();
audioViewUpdate();
audioElementUpdatePlayButton();
audioAnalyserInitialize();
}, 250);
}
}
And
var audioTimeUpdate = function () {
'use strict';
if (audioSource.paused === false) {
audioSetProperties();
createCookie('track_time', audioSource.currentTime, 360);
setTimeout(function () {
audioTimeUpdate();
}, 500);
}
};
Create the cookie containing the AudioTrack object (source, name, etc)
// Play the track that is being viewed
var audioPlayFromView = function () {
'use strict';
audioCurrent = audioFromView;
var audioCurrentString = JSON.stringify(audioCurrent);
createCookie('track', audioCurrentString, 360);
audioCurrent.setSrc();
audioCurrent.play();
if (analyserInitialized === true) {
source.disconnect();
source = context.createMediaElementSource(audioSource);
}
audioViewUpdate();
};

Create array in cookie with javascript

Is it possible to create a cookie using arrays?
I would like to store a[0]='peter', a['1']='esther', a['2']='john' in a cookie in JavaScript.
As you can read in this topic:
You combine the use jQuery.cookie plugin and JSON and solve your problem.
When you want to store an array, you create an array in JS and use JSON.stringify to transform it into an string and stored with $.cookie('name', 'array_string')
var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));
When you want to retrive the array inside the cookie, you use $.cookie('name') to retrive the cookie value and use JSON.parse to retrive the array from the string.
var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]
Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
You could do this with a JSON library.
I add the code below Script (see the following code) into a javascript file called CookieMonster.js.
It's a wrapper around the current snippet from http://www.quirksmode.org/js/cookies.html
It works with arrays and strings, it will automagically escape your array/string's commas , and semi-colons ; (which are not handled in the original snippets).
I have listed the simple usage and some bonus usage I built into it.
Usage:
//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30);
var seriesarray = cookiemonster.get('series'); //returns array with the above numbers
//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30);
var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'
Bonuses:
//It also conveniently contains splice and append (works for string or array (single string add only)).
//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this'
//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']
//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']
CookieMonster.js :
var cookiemonster = new Object();
cookiemonster.append = function (cookieName, item, expDays) {
item = cm_clean(item);
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue[cookievalue.length] = item;
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
} else {
cm_createCookie(cookieName, cookievalue + item, expDays);
}
};
cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue.splice(index, numberToRemove);
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
}
};
cookiemonster.get = function (cookieName) {
var cstring = cm_readCookie(cookieName);
if (cstring.indexOf('<#&type=ArrayVals>') != -1) {
var carray = cstring.split(',');
for (var i = 0; i < carray.length; i++) {
carray[i] = cm_dirty(carray[i]);
}
if (carray[0] == '<#&type=ArrayVals>') {
carray.splice(0, 1);
}
return carray;
} else {
return cm_dirty(cstring);
}
};
cookiemonster.set = function (cookieName, value, expDays) {
if (value instanceof Array) {
cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
}
else { cm_createCookie(cookieName, cm_clean(value), expDays); }
};
cookiemonster.eraseCookie = function (name) {
cm_createCookie(name, "", -1);
};
function cm_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
};
function cm_clean(ret) {
ret = cm_replaceAll(ret.toString(), ',', '&#44');
ret = cm_replaceAll(ret.toString(), ';', '&#59');
return ret;
};
function cm_dirty(ret) {
ret = cm_replaceAll(ret, '&#44', ',');
ret = cm_replaceAll(ret, '&#59', ';');
return ret;
};
function cm_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 cm_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 cm_arrayAsString(array) {
var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
for (var i = 0; i < array.length; i++) {
ret = ret + "," + cm_clean(array[i]);
}
return ret;
};
Create array in cookie using jQUery?
var list = new cookieList("test"); $(img).one('click', function(i){ while($('.selected').length < 3) {
$(this).parent()
.addClass("selected")
.append(setup.config.overlay);
//$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
var index = $(this).parent().index();
// suppose this array go into cookies.. but failed
list.add( index );
var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
if( $('.total').length ){
$('.total').html(count);
}
} });
I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:
var a = ['peter','esther','john'];
You could define a cookie string, then iterate over the array:
// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();
// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';
// Loop over the array
for(var i=0;i<a.length;i++) {
cookieStr += a[i]+',';
}
// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);
// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;
In this example, you would get the following cookie stored (if your domain is www.example.com):
arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com
I've created this easy way to get cookies. It'll give error if execute here, but it's functional
var arrayOfCookies = [];
function parseCookieToArray()
{
var cookies = document.cookie;
var arrayCookies = cookies.split(';');
arrayCookies.map(function(originalValue){
var name = originalValue.split('=')[0];
var value = originalValue.split('=')[1];
arrayOfCookies[name] = value;
});
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();
New
My new obj to create get cookies
cookie = {
set: function(name, value) {
document.cookie = name+"="+value;
},
get: function(name) {
cookies = document.cookie;
r = cookies.split(';').reduce(function(acc, item){
let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
c[0] = c[0].replace(' ', ''); //remove white space from key cookie
acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
return acc; //here do not return to r variable, here return to accumulator
},[]);
}
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');
Here's the simplest form of adding a cookie in array format.
function add_to_cookie(variable, value) {
var d = new Date();
d.setTime(d.getTime() + (90 * 24 * 60 * 60 * 1000)); //equivalent to 1 month
var expires = "expires=" + d.toUTCString();
document.cookie = "cookie_name[" + variable + "]" + "=" + value + ";" + expires + ';path=/';
}
For that example you can do it quite easily:
Make Cookies:
///W3Schools Cookie Code:
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 + ";";
}
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 "";
}
///My Own Code:
for(a=0;a<b.length;a++){
setCookie(b[a],b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
b[a] = getCookie(b[a])
}
For any array with other value types besides strings:
Make Cookies:
///Replace MyCode above With:
if(typeof b[a] === 'string'){
setCookie(b[a],b[a],periodoftime);
}else{
setCookie(b[a].toString,b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
if(typeof b[a] === 'string'){
b[a] = getCookie(b[a])
}else{
b[a] = getCookie(b[a].toString)
}
}
The only flaw is that identical values cannot be retrieved.
No JQuery needed, comma seperation or JSON.
Added remove to cookiemonster
// remove item
cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8']
cookiemonster.remove = function (cookieName, item, expDays) {
var cookievalue = cookiemonster.get(cookieName);
//Find the item
for( var i = 0; i < cookievalue.length; i++) {
if ( cookievalue[i] === item) {
cookievalue.splice(i, 1);
}
}
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
};
You can save a lot of data within a single cookie and return it as an array, try this
function setCookie(cookieKey, cookieValue) {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
idPurchase.push(cookieValue)
document.cookie = cookieKey+"=" + idPurchase
console.log("Id das compras efetuadas :",idPurchase)
$("#purchases_ids option:last").after($('<option onclick="document.getElementById("input_class1").value='+cookieValue+'" value="'+cookieValue+'">'+cookieValue+'</option>'))
}
checkCookie()
function checkCookie() {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
console.log("Id das compras efetuadas :",idPurchase)
for (i = 1; i < idPurchase.length; i++) {
$("#purchases_ids option:last").after($('<option value="'+idPurchase[i]+'">'+idPurchase[i]+'</option>'))
}
purchases_ids.addEventListener("change",changeSpeed)
}
in this project that I created I store values ​​in arrays, codePen is not allowing the storage of cookies, but in the example below you can get a complete picture, just study the implementation
Github project
Open in Gitpod

Categories

Resources