Variable passed as parameter returning undefined JS - javascript

I am trying to pass a variable which stores a cookie name in JS, the correct value is stored when writing the cookie but when passed to the function to read the cookie it returns undefined, returning the cookie value as NULL. It is for a college project, and I am working from the code example on this site here https://www.quirksmode.org/js/cookies.html
function WriteCookie(cname, username) {
//Cookies variables
var cname = 'user';
var username = document.getElementById("username").value;
//check if the user has entered a value and alert if they haven't
if (document.myform.username.value == "") {
alert("Please enter a value in the name field");
document.getElementById("username").focus();
return false
}
//variables for emial validation
var emailtext = document.myform.email.value;
var pos_of_at = emailtext.indexOf('#');
//checking email address for an #
if (pos_of_at <= 0) {
alert("Invalid Email");
document.getElementById("email").focus();
return false;
}
//store the cookie
document.cookie = cname + "=" + username + "; path=/";
location.href = 'welcome.html';
}
//function to read the cookie
function readCookie(cname) {
//variable for loop
var nameEQ = 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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
}
return null;
}
function cookiealert() {
alert(readCookie());
}

It is possible that you're using httponly cookie causing this.
From MDN docs:
A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.
Therefore, your for loop does not return any value and the function returns back null.

Related

Having some trouble with setting and getting cookies

I'm working on a quiz app as part of my college course and have ran into a bit of a roadblock. The code below is for few functions I've wrote. These are supposed to take the user input from the name and email fields, validate the email and store the name as a cookie to be displayed on another page.
I've got this working for the most part, but I'm having trouble getting the stored cookie value to display correctly. It is loading, but is showing as undefined=ryan. If I type a longer name, less and less of the string is displayed. I think there's an issue with the section where I've tried to split the string, but I can't figure it out for the life of me.
Any help or advice would be greatly appreciated.
Thanks :)
function setCookie(cname, cvalue)
{
let userValue = document.getElementById("email").value;
let pos_of_at = userValue.indexOf("#");
if (userValue == " " || pos_of_at<0)
{
alert("You must enter a valid email address");
document.getElementById("email").focus();
}
else
{
cvalue=document.getElementById("userName").value;
document.cookie= cname + " = " + cvalue + ";";
window.location.href="/quiz.html"
}
}
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];
c = c.trim();
if (c.indexOf(c) ==0)
{
return c.substring(name.length, c.length);
}
}
return "cookie not found";
}
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Figured it out. Issue was the checkCookie function.
Was
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Should have been
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie();
}

how to use document and Request.Cookies

I have two variables which needs to be created as a cookie. Can I give them just as without giving any expiration date but just as a key value pair,
document.cookie = "<%= this.CookieDFKey %> = id";
alert (document.cookie);
document.cookie = "<%= this.CookieDateCompleteEnd %> = lastRunDate";
window.location = '<%= ResolveUrl("~/GUI/DRNEW.aspx") %>';
When I gave the alert statement to check what value it is having it shows me
I need to have both the values id and lastRunDate avaiable in the called page. Can I be just using Request.Cookie[the name of cookie where the value store]?
First cookies are key value pairs, you will get all cookies in Request.Cookies
If i'm not wrong in C#
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["Font"] != null)
{ userSettings = Request.Cookies["UserSettings"]["Font"]; }
}
Read the below url to set multiple cookies in document.cookie
Setting multiple cookies in Javascript
document.cookie = "id=<%= this.CookieDFKey %>";
document.cookie = "lastRunDate=<%= this.CookieDateCompleteEnd %> ";
To retrieve cookie use the following code
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 "";
}

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;

Cookies returning undefined

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

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

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

Categories