Related
So i'm trying a simple cookie exercise and when i hit submit it returns undefined. Also is there a way to check what in a cookie in visual studio code?
function setcookie()
{
var tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
document.cookie = "username="+ document.getElementById("username").innerHTML +";path=/";
document.cookie = "password="+ document.getElementById("password").value +";path=/";
}
function getcookie()
{
var Carray = document.cookie.split(";");
for(i = 0 ; i < Carray.length ; i++)
{
var valuearray =Carray[i].split("=")
if (valuearray == "username")
{
var name = valuearray[1];
}
else if (valuearray == "password")
{
var password = valuearray[1];
}
}
alert("username is " + name +" password is " + password);
}
valuearray will be a array, so you need to check valuearray[0] in the if condition.
var valuearray = Carray[i].split("=")
if (valuearray[0] == "username"){ //Here, valuearray[0]
var name = valuearray[1];
} else if (valuearray[0] == "password"){
var password = valuearray[1];
}
Try this
function getcookie() {
const Carray = document.cookie.split(";");
const [name, password] = Carray.map(item => item.split('=')[1])
console.log("username is " + name +" password is " + password);
}
or if you want to transform your cookies into object use this code
function getcookie()
{
var Carray = document.cookie.split(";");
var cookieObj = Carray.reduce((cookieObj, current) => {
const [key, value] = current.split('=');
return { ...cookieObj, ...{ [key]: value } }
}, {})
console.log("username is " + cookieObj.username +" password is " + cookieObj.password);
return cookieObj;
}
// result
{
username: 'usersname'
password: 'userspassword'
}
Please return your result from the functions, I'm not returning anything because I'm trying to match your code.
and answer to your second question. yes you can get value from vscode but for that you need to start your debugging mode
name and password are declared in the block of for, but you use them in out of the block.
change getcookie function to this:
var name="";
var password ="";
for(i = 0 ; i < Carray.length ; i++)
{
var valuearray =Carray[i].split("=")
if (valuearray == "username")
{
name = valuearray[1];
}
else if (valuearray == "password")
{
password = valuearray[1];
}
}
alert("username is " + name +" password is " + password);
I'm trying to figure out the best fallback method for storing data when someone visits our site. We use this to store search filter preferences in particular, that need to move across the site as they move around. Ideally it would work with:
localStorage first
fallback to sessionStorage
then fallback to cookies
My current setup looks a bit like:
var localStorageAvail = supports_html5_storage();
var storage = "local";
if (localStorageAvail == undefined || localStorageAvail == false || localStorageAvail == null) {
storage = "cookie";
}
function supports_html5_storage() {
var testKey = 'test', storage = window.localStorage;
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
return true;
} catch (error) {
return false;
}
}
function getValue(what) {
if (storage == "cookie") {
// get from cookie
return readCookie(what);
} else {
// localstorage
return localStorage.getItem(what)
}
}
function setValue(what,value) {
if (storage == "cookie") {
// get from cookie
writeCookie(what,value,365);
} else {
// localstorage
localStorage.setItem(what,value)
}
}
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 writeCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
FWIW, I'm not using jQuery, and I don't want to have to include extra libraries to do this. It needs to all be in Vanilla JS :)
My question: What is the best way to do this? Should I just tweak my current method, so it includes sessionStorage as well? Or are there better methods to do this?
I have two Angular services. The first creates a cookie and the second sets a URL to include the created cookie. I need the first to run before the second. Normally this is not an issue when using a service as my services tend to use a http call that has a success output, but in this instance, I don't have a success call and I don't know how I can trigger that the first is complete. Here is my code as it stands:
// Set Session Cookie
appCheckCookie.getCookie();
// Get Cart URL with Session Cookie
$scope.cartURL = appCartURL.getCartURL();
I have tried wrapping these in their own functions and trying to execute them in order, but that didn't work. and I tried something like this, but it didn't work:
appCheckCookie.getCookie(function(){
$scope.cartURL = appCartURL.getCartURL();
});
Here are my two services:
appServices.factory('appCheckCookie', ['$http', function ($http) {
var getCookie = function () {
// Create session cookie
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 to read cookie
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;
}
var x = readCookie('ppkcookie')
if (x == null) {
// Get Session ID from backend URL
$http.post('/getSession', {}).success(function (data) {
// Create cookie from session ID from backend. Note that setting the days to 0 deletes the cookie on browser close (recommended)
createCookie('ppkcookie', data, 0);
console.log("Cookie Created: " + data);
}, function (err) {
console.log(err);
});
}
else {
var data = readCookie('ppkcookie');
console.log("Cookie Exists: " + data);
}
};
return {
getCookie: getCookie
};
}]),
appServices.factory('appCartURL', ['$http', function ($http) {
var getCartURL = function () {
// Function to read cookie
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;
}
var x = readCookie('ppkcookie')
var baseCartURL = 'http://myecommsite.net/basket.html?Session_ID='
var cartURL = baseCartURL + x;
return cartURL;
};
return {
getCartURL: getCartURL
};
}]),
In case of handling Async operations, Promise should be one of the APIs to consider.
What is Promise?
This may give you some inspirations of how to use it in your case:
// Namespace YourService
function readCookie(name) {
return new Promise(function(resolve, reject){
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)
resolve(c.substring(nameEQ.length, c.length));
}
resolve(null); // consider reject(null)?
});
}
// Run in service
YourService.readCookie(name).then(function(cookieResponse) {
// Run your second service after cookie retrieved
}).catch(function(reason) {
// Catch reject
});
Another thing needs to be mentioned would be IE does not support Promise natively(Of course it doesn't..), so to use it in IE, you need to apply a polyfill.
Hope this can help.
Great advice on the use of $q. Along with a colleague, this is working since we only need the 1st service to signal that it is complete:
appServices.factory('appCheckCookie', ['$q', '$http', function ($q, $http) {
var getCookie = function () {
var deferred = $q.defer();
// Create session cookie
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 to read cookie
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;
}
var x = readCookie('ppkcookie')
if (x == null) {
// Get GUID for the cookie
$http.post('/getSession', {}).success(function (data) {
// Create cookie. Note that setting the days to 0 deletes the cookie on browser close (recommended)
createCookie('ppkcookie', data, 0);
console.log("Cookie Created: " + data);
deferred.resolve(data);
}, function (err) {
console.log(err);
});
}
else {
var cookieExists = readCookie('ppkcookie');
console.log("Cookie Exists: " + cookieExists);
deferred.resolve(cookieExists);
}
return deferred.promise;
};
return {
getCookie: getCookie
};
}]),
Then in the controller:
appCheckCookie.getCookie().then(function (data) {
// Get Cart URL
$scope.cartURL = appCartURL.getCartURL();
console.log($scope.cartURL);
});
Hi i am using phone gap technology for blackberry development . i want to call soap based xml .when i run html page on internet explore web service response will come but when i run in simulator or device no response will come.Please help.thanks in advance .i used java script.
/*
Javascript "SOAP Client" library
#version: 2.1 - 2006.09.08
#author: Matteo Casati - http://www.guru4.net/
*/
var arr = new Array();
var arrayIndex;
arrayIndex = 0;
function SOAPClientParameters()
{
var _pl = new Array();
this.add = function(name, value)
{
_pl[name] = value;
return this;
}
this.toXml = function()
{
var xml = "";
for(var p in _pl)
xml += "<" + p + ">" + SOAPClientParameters._serialize(_pl[p]) + "</" + p + ">";
return xml;
}
}
SOAPClientParameters._serialize = function(o)
{
var s = "";
switch(typeof(o))
{
case "string":
s += o.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); break;
case "number":
case "boolean":
s += o.toString(); break;
case "object":
// Date
if(o.constructor.toString().indexOf("function Date()") > -1)
{
var year = o.getFullYear().toString();
var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
var milliseconds = o.getMilliseconds().toString();
var tzminutes = Math.abs(o.getTimezoneOffset());
var tzhours = 0;
while(tzminutes >= 60)
{
tzhours++;
tzminutes -= 60;
}
tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
}
// Array
else if(o.constructor.toString().indexOf("function Array()") > -1)
{
for(var p in o)
{
if(!isNaN(p)) // linear array
{
(/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
var type = RegExp.$1;
switch(type)
{
case "":
type = typeof(o[p]);
case "String":
type = "string"; break;
case "Number":
type = "int"; break;
case "Boolean":
type = "bool"; break;
case "Date":
type = "DateTime"; break;
}
s += "<" + type + ">" + SOAPClientParameters._serialize(o[p]) + "</" + type + ">"
}
else // associative array
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">"
}
}
// Object or custom function
else
for(var p in o)
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">";
break;
default:
throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
}
return s;
}
function SOAPClient() {}
SOAPClient.invoke = function(url, method, parameters, async, callback)
{
if(async)
SOAPClient._loadWsdl(url, method, parameters, async, callback);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if(wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
// get namespace
var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
alert(ns);
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", soapaction);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
}
xmlHttp.send(sr);
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Response");
alert("ND " +nd);
if(nd.length == 0)
{
if(req.responseXML.getElementsByTagName("faultcode").length > 0)
{
if(async || callback)
o = new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
else
throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
} else {
}
}
else{
o = SOAPClient._soapresult2object(nd[0], wsdl);
}
if(callback){
callback(arr);
}
if(!async)
return o;
}
SOAPClient._soapresult2object = function(node, wsdl)
{
var wsdlTypes = SOAPClient._getTypesFromWsdl(wsdl);
return SOAPClient._node2object(node, wsdlTypes);
}
SOAPClient._node2object = function(node, wsdlTypes)
{
if(node == null)
{
return null;
}
// text node
if(node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdlTypes);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdlTypes);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdlTypes).toLowerCase().indexOf("arrayof") != -1;
// object node
if(!isarray)
{
var obj = null;
if(node.hasChildNodes())
{
obj = new Object();
for(var i = 0; i < node.childNodes.length ; i++)
{
var p = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
if((node.childNodes[i].nodeName.toLowerCase().indexOf("Return") == -1) && (node.childNodes[i].nodeName.toLowerCase().indexOf("Response") == -1))
{
obj[node.childNodes[i].nodeName] = p;
}
}
arr[arrayIndex++] = obj;
}
return obj;
}
// list node
else
{
//create node ref
var l = new Array();
for(var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
return l;
}
return null;
}
SOAPClient._extractValue = function(node, wsdlTypes)
{
var value = node.nodeValue;
switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdlTypes).toLowerCase())
{
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if(value == null)
return null;
else
{
value = value + "";
value = value.substring(0, (value.lastIndexOf(".") == -1 ? value.length : value.lastIndexOf(".")));
value = value.replace(/T/gi," ");
value = value.replace(/-/gi,"/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypesFromWsdl = function(wsdl)
{
var wsdlTypes = new Array();
// IE
var ell = wsdl.getElementsByTagName("s:element");
var useNamedItem = true;
// MOZ
if(ell.length == 0)
{
ell = wsdl.getElementsByTagName("element");
useNamedItem = false;
}
for(var i = 0; i < ell.length; i++)
{
if(useNamedItem)
{
if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("type") != null)
wsdlTypes[ell[i].attributes.getNamedItem("name").nodeValue] = ell[i].attributes.getNamedItem("type").nodeValue;
}
else
{
if(ell[i].attributes["name"] != null && ell[i].attributes["type"] != null)
wsdlTypes[ell[i].attributes["name"].value] = ell[i].attributes["type"].value;
}
}
return wsdlTypes;
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdlTypes)
{
var type = wsdlTypes[elementname] + "";
return (type == "undefined") ? "" : type;
}
// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
try
{
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
}
catch (ex) {}
// old XML parser support
return document.getElementsByTagName(tagName);
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function()
{
try
{
if(window.XMLHttpRequest)
{
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if(req.readyState == null)
{
req.readyState = 1;
req.addEventListener("load",
function()
{
req.readyState = 4;
if(typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
if(window.ActiveXObject)
return new ActiveXObject(SOAPClient._getXmlHttpProgID());
}
catch (ex) {}
throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
if(SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for(var i = 0; i < progids.length; i++)
{
try
{
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
xmlParsingDataReturn=function(){
return arr;
}
As a WebWorks app, you are required to whitelist any external domains you will be accessing through your app. Since this works on a computer's browser but not on an actual device or on the simulator, it may be an issue with the config file. See the PhoneGap site for more info on whitelisting.
What's a good way to check if a cookie exist?
Conditions:
Cookie exists if
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
Cookie doesn't exist if
cookie=;
//or
<blank>
You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.
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));
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
I have crafted an alternative non-jQuery version:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
It only tests for cookie existence. A more complicated version can also return cookie value:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
Put your cookie name in in place of MyCookie.
document.cookie.indexOf('cookie_name=');
It will return -1 if that cookie does not exist.
p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name
(Source)
This is an old question, but here's the approach I use ...
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
This returns null either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.
A cookie should never exist without a value -- because, in all fairness, what's the point of that? 😄
If it's no longer needed, it's best to just get rid of it all together.
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
ATTENTION!
the chosen answer contains a bug (Jac's answer).
if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!
here is a revised version of that function:
function getCookie( name ) {
var dc,
prefix,
begin,
end;
dc = document.cookie;
prefix = name + "=";
begin = dc.indexOf("; " + prefix);
end = dc.length; // default to end of the string
// found, and not in first position
if (begin !== -1) {
// exclude the "; "
begin += 2;
} else {
//see if cookie is in first position
begin = dc.indexOf(prefix);
// not found at all or found as a portion of another cookie name
if (begin === -1 || begin !== 0 ) return null;
}
// if we find a ";" somewhere after the prefix position then "end" is that position,
// otherwise it defaults to the end of the string
if (dc.indexOf(";", begin) !== -1) {
end = dc.indexOf(";", begin);
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}
If you're using jQuery, you can use the jquery.cookie plugin.
Getting the value for a particular cookie is done as follows:
$.cookie('MyCookie'); // Returns the cookie value
regexObject.test( String ) is faster than string.match( RegExp ).
The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Tests
function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));
Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie (which all of the answers are using). Such cookie can be checked only at sever side.
instead of the cookie variable you would just use document.cookie.split...
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}
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{
var oneCookie = dc.indexOf(';', begin);
if(oneCookie == -1){
var end = dc.length;
}else{
var end = oneCookie;
}
return dc.substring(begin, end).replace(prefix,'');
}
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
var fixed = dc.substring(begin, end).replace(prefix,'');
}
// return decodeURI(dc.substring(begin + prefix.length, end));
return fixed;
}
Tried #jac function, got some trouble, here's how I edited his function.
For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie module!
First install the cookie module (and save as a dependency):
npm install --save cookie
Then import and use:
import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed)
console.log(parsed.cookie1);
Using Javascript:
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
Parse cookies with Array.prototype.reduce() into an object (ES6)
const cookies = document.cookie.split(";").reduce((e, t) => {
const [c, n] = t.trim().split("=").map(decodeURIComponent);
try { // this can be removed if you do not need JSON cookies parsed
return Object.assign(e, {
[c]: JSON.parse(n)
})
}
catch (t) {
return Object.assign(e, {
[c]: n
})
}
}, {})
Check if your cookie is there
typeof cookies.yourCookie === "string";
If anyone is still looking into this post maybe this will help.
First do a function to get the cookie, something like this..
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.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 "";
}
Then you could check if the specific cookie exists before doing something else
if( getCookie(mycookieName)){
// do something....
}
// check if cookie is present
function is_CookiePresent( cookieName ){
if( void 0 != cookieName && "" != cookieName && null != cookieName ){
var is_present = document.cookie.split(";").filter(e=>{
if(e.trim().split("=").includes(cookieName)) return true;
})
if(!is_present.length){return false;}
return true;
}
else{
return false;
}
}
// Get cookie name value :)
function getCookieValue( cookieName ){
if( void 0 != cookieName && "" != cookieName && null != cookieName ){
var is_present = document.cookie.split(";").filter(e=>{
if(e.trim().split("=").includes(cookieName)) return true;
})
if(!is_present.length){return false;}
var __CookieValue = is_present.join('').trim();
return __CookieValue.substring(__CookieValue.indexOf('=')+1);
}
else{
return false;
}
}
use this method instead:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
else return null;
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
/// ************************************************ cookie_exists
/// global entry point, export to global namespace
/// <synopsis>
/// cookie_exists ( name );
///
/// <summary>
/// determines if a cookie with name exists
///
/// <param name="name">
/// string containing the name of the cookie to test for
// existence
///
/// <returns>
/// true, if the cookie exists; otherwise, false
///
/// <example>
/// if ( cookie_exists ( name ) );
/// {
/// // do something with the existing cookie
/// }
/// else
/// {
/// // cookies does not exist, do something else
/// }
function cookie_exists ( name )
{
var exists = false;
if ( document.cookie )
{
if ( document.cookie.length > 0 )
{
// trim name
if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
{
var cookies = document.cookie.split ( ";" );
var name_with_equal = name + "=";
for ( var i = 0; ( i < cookies.length ); i++ )
{
// trim cookie
var cookie = cookies [ i ].replace ( /^\s*/, "" );
if ( cookie.indexOf ( name_with_equal ) === 0 )
{
exists = true;
break;
}
}
}
}
}
return ( exists );
} // cookie_exists
function getcookie(name = '') {
let cookies = document.cookie;
let cookiestore = {};
cookies = cookies.split(";");
if (cookies[0] == "" && cookies[0][0] == undefined) {
return undefined;
}
cookies.forEach(function(cookie) {
cookie = cookie.split(/=(.+)/);
if (cookie[0].substr(0, 1) == ' ') {
cookie[0] = cookie[0].substr(1);
}
cookiestore[cookie[0]] = cookie[1];
});
return (name !== '' ? cookiestore[name] : cookiestore);
}
To get a object of cookies simply call getCookie()
To check if a cookie exists, do it like this:
if (!getcookie('myCookie')) {
console.log('myCookie does not exist.');
} else {
console.log('myCookie value is ' + getcookie('myCookie'));
}
Or just use a ternary operator.
function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}
Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
You can verify if a cookie exists and it has a defined value:
function getCookie(cookiename) {
if (typeof(cookiename) == 'string' && cookiename != '') {
const COOKIES = document.cookie.split(';');
for (i = 0; i < COOKIES.length; i++) {
if (COOKIES[i].trim().startsWith(cookiename)) {
return COOKIES[i].split('=')[1];
}
}
}
return null;
}
const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value
It will return null if cookie doesn't exists.