Javascript - How to display only the value of a cookie? - javascript

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) : ""
}

Related

Javascript getCookie function doesn't work properly

I'm simply trying to read a cookie's value, but I seem to be doing something wrong, but I don't see the problem. The cookie does get properly stored and can be accessed under document.cookie, so that's not the problem. Here's my JS code:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
var value = getCookie(value);
console.log(value);
console.log(document.cookie);
d = new Date('20 Oct 2022')
function setCookie() {
document.cookie = `value=10000; expires=${d.toUTCString()}`;
console.log("cookie set!");
}
edit: I found my problem. I was missing the quotation marks… I've never felt this stupid :D
You can use this function:
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

How to create page visit counting like PHP session on JavaScript (client) side

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>

Logical Operator always stays true?

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);

how to add token value to URL and pass it without allowing any extra characters to be added?

Hi I am trying to get token value from cookie and add it to the URL but extra characters like *(asterisk) are being added. please help me how should i pass my token value in URL without adding any characters.
here is my javascript code
urls.put("AppName", "javascript:submitApplication()");
function submitApplication() {
var cookieToken = "SSOCookie";
var newToken = GetCookie(cookieToken);
myWindow = window.open(myhost + "/webapp/sso?ssotype=type1&appname=APP1&mode=ARD&newToken="+newToken,'ApplicationName');
myWindow.focus();
}
My newToken value is added with stars as below
https://test.test1.com/webapp/sso?ssotype=type1&appname=APP1&mode=ARD&newToken=AQIC5wM2LY4SfczjfZ-64LqYUNHjjYVmu13iznLg1gKZoas.*AAJTSQACMDIAAlNLABM2MTI2ODc1MDg4MDc4MzE0NjI0AAJTMQACMDY.**
But i want this to be passed as ( without adding any characters)
https://test.test1.com/webapp/sso?ssotype=type1&appname=APP1&mode=ARD&newToken=AQIC5wM2LY4SfczjfZ-64LqYUNHjjYVmu13iznLg1gKZoas.AAJTSQACMDIAAlNLABM2MTI2ODc1MDg4MDc4MzE0NjI0AAJTMQACMDY.
Please help me how can i pass this token value in URL without allowing any extra characters to be added . Thank you
I would do something like this:
Make a function that accepts a cookie name, to retrieve the cookie you're looking for.
function getCookie(cookieName) {
var name = cookieName + '=';
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 '';
}
Then whenever you need to get that cookie, you just need to declare a variable and call that function.
var myCookie = getCookie('name_of_the_cookie');
Add the cookie to the url.
var basicUrl = 'https://www.google.dk';
var fullUrl = basicUrl + '/' + myCookie;

get and set cookie values in array position

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.

Categories