What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?
Can you people please have a look over it :
<script type="text/javascript">
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
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);
}
var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];
//jsonObj.push("test");
var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
if (pathname != res[i]) {
alert("IS NOT EQUAL");
//res.push(pathname);
//var joinedArray = res.join(",");
//console.log(joinedArray);
//createCookie('vid_cookies',joinedArray,7);
//var z = readCookie('vid_cookies');
//console.log(z)
}
}
} else {
jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}
//alert(jsonObj);
</script>
Here is the Array as :
["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.
In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.
One way to do it would be to use Array#every:
if (res.every(x => x !== pathname)) {
// add to array and set cookie
}
Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:
var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);
Related
Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
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(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=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>
Desperately reaching out here now!
My webpage contains three columns with three different divs: "primary", "main" and "secondary".
I would like to maintain the scrollpositions of all divs on reload.
For the the first column "primary" I'm using this script below, that works lika a charm.
I know getElementbyID only can get one div, so how could I possibly do?
window.onload = function() {
var strCook = document.cookie;
if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.getElementById("primary").scrollTop = strPos;
}
}
function SetDivPosition() {
var intY = document.getElementById("primary").scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}
The way that you set the cookie seems to be set up primarily for one item - I would change this so that you can set cookies by a key value pairing.
Using some functions for getting and setting cookies, I would then change your code to:
//add cookie functions
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 "";
}
//I am assuming you will have some sort of on scroll function for setting your cookie. Change this to a function so you can bind it multiple times
function bindScrollEvent(elementId) {
var element = document.getElementById(elementId);
element.onscroll = function() {
setCookie(elementId, element.scrollTop); // use the element id to set the cookie to the scrolltop value
};
// once the event is bound, you can set it's current scroll position
var scrollTopPosition = getCookie(elementId);
if (scrollTopPosition !== '') {
element.scrollTop = scrollTopPosition;
}
}
// reload the div positions when the document loads
window.onload = function() {
bindScrollEvent('primary');
bindScrollEvent('secondary');
bindScrollEvent('main');
}
I'm building a small HTML game that uses cookies/localStorage to save and load users data. I have an object declared that holds all of the data which is then referenced by the save/load functions and by game calculations:
var iAttack, iDefence, iGold;
// nothing to do with Apple lol...
var data = {
pStats: {
attack: iAttack,
defence: iDefence
},
pInventory: {
gold: iGold
}
}
These will obviously return undefined, but this is before the cookie values are inserted.
So, heres a run-through of whats supposed to happen:
When the window loads, the if statements are gone through to check cookies/localStorage and if there is any previous storage data in the browser. These booleans get assigned to cookies, storageLocal and previousData. This is the code for it:
var previousData = false;
var cookies = false;
var storageLocal = false;
//activated on window.load
function loadData(){
//check for previous data
if (document.cookie != "") {
previousData = true;
console.log("Previous data? " + previousData)
} else if (localStorage.getItem("gold") !== null) {
previousData = true;
console.log("Previous data? " + previousData)
} else {
console.log("Previous data? " + previousData)
}
// check if cookies/localStorage
document.cookie = "foo=bar";
if(document.cookie){
cookies = true;
console.log("Cookies will be used")
} else if (typeof(localStorage) != undefined){
storageLocal = true;
console.log("localStorage will be used")
}
// loadData() continued...
If previousData = false then default values are assigned to the object variables, eg iDefence = 5 and this works fine.
Lets assume that previousData and cookies are true: the function then goes on to inserting the data from the cookies into the object variables like this:
if (previousData) {
if (cookies){
data.pStats.attack = parseInt( readCookie("attack") );
data.pStats.defence = parseInt( readCookie("defence") );
// note that i've used iAttack instead of data.pStats.attack but doesn't work
In the console, if i input iAttack or data.pStats.attack it returns undefined. This is the problem that been keeping me up all of last night trying to work around. Any help would be really appreciated.
This is the saveData function that is triggered by onclick. It inputs the object values into cookies:
function saveData(){
if(cookies){
createCookie("attack", iAttack, 7);
createCookie("defence", iDefence, 7);
//if its the first time saving then the default values of iAttack/def will be used
If you're curious about createCookie() and readCookie(), these are the functions:
function 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 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);
}
I have searched several places trying to find out how to do display only the value of a cookie rather than the whole key but they all seemed needlessly complex for what I'm doing. I've got a single cookie with only one key, userName = something, and I can't figure out how to display only the "something" rather than userName = something.
function userCookie(form)
{
if(form.User_Name.value == "")
{
alert("Cannot accept a blank user name, please enter a valid name");
return false;
}
else
{
document.cookie="userName=" + form.User_Name.value;
alert(document.cookie);
return false;
}
}
function newWindow()
{
var userWindow = window.open("","MyUserName","height=300,width=300");
userWindow.document.open();
userWindow.document.write("<p>Welcome Back</p>");
userWindow.document.write(document.cookie);
userWindow.document.close();
}
If you always have exactly one cookie then document.cookie.split("=")[1] would be simple enough.
document.cookie will always return key,value pair like cookie1=value1;cookie2=value2.
You can use the following function to split the cookieName and "=" from the document.cookie to get the value.
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 "";
}
The code is from w3schools.
var cookieArray = document.cookie.split("; "),
cookieObject = {},
i, pair;
for (i = cookieArray.length - 1; i >= 0; i--) {
pair = cookieArray[i].split("=");
cookieObject[pair[0]] = pair[1];
}
alert(cookieObject.userName);
function getCookie(name) {
let x = document.cookie.split(";").find(a => a.includes(name + "="));
return !!x ? x.trim().substr(name.length+1) : ""
}
OK, I have the logic, but unsure how to write to specific positions in a cookie that are separated with a pipe, |
For example - take a cookie with 0|0|0|0
if global variable is set to Y, then write the values c and d to the 2nd & 3rd position(assuming array) if the cookie exists - if the cookie doesn't exist then create a cookie with 0|0|c|d
if the global variable is null then write the values a and b to the 0 and 1st position if the cookies exists - if the cookie doesn't exist then create a cookie with a|b|0|0
I understand getting a cookie, and splitting the cookie to get a value, but unsure how to write to specific positions. I'm assuming using "join".
function 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 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);
}
Assuming your desired cookie value was named "pipes" and your variable was named globalVar, you could do something like this:
var val = readCookie("pipes") || "";
var valArray = val.split("|");
if (valArray.length >= 4) {
if (globalVar == "Y") {
valArray[2] = 'c';
valArray[3] = 'd';
} else if (globalVar == null) {
valArray[0] = 'a';
valArray[1] = 'b';
}
val = valArray.join("|");
} else {
// fully formed cookie value didn't exist
if (globalVar == "Y") {
val = "0|0|c|d";
} else {
val = "a|b|0|0";
}
}
createCookie("pipes", val, 365);
I must say that storing this piped value in the cookie is very inconvenient and requires more code than is probably required to just store and retrieve multiple values from a cookie.
From your comments, it sounds like the data is storeID|storeLocation and you have two of those. I'd suggest you just do this:
var store1 = readCookie("store1"); // "1640|Jacob's Point"
var store2 = readCookie("store2"); // "2001|Fred's Point"
Or, if you want to make a function, you can do this:
function readStoreInfo(item) {
var info = readCookie(item);
if (info) {
var data = info.split("|");
return({id: data[0], name: data[1]});
}
return(null);
}
function writeStoreInfo(item, obj) {
var val = obj.id + "|" + obj.name;
createCookie(item, val, 365);
}
So, to read the data for store1, you would just call:
var store1Info = readStoreInfo("store1");
store1Info.id = 123;
writeStoreInfo("store1", store1Info);
You can then read and write the data for store1 and store2 independently.