I've been trying to use 2 cookies and I changed all the variables and it still won't work only one cookie will work and if I remove the code for the first cookie the second one will work and vise vira. Someone please help me get this going.
var setCookie = function (n, val) {
var exdays = 365;
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = n + "=" + val + "; " + expires;
};
var getCookie = function (n) {
var name = n + "=";
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 "";
};
document.onclick = function (e) {
if (e.target.className == 'btn') {
var favColor = e.target.style.background;
setCookie('color', favColor);
document.getElementsByClassName('body-separator4')[0].style.background = favColor;
console.log(favColor);
}
};
window.onload = function () {
var favColor = document.getElementsByClassName("body-separator4")[0].style.background
var color = getCookie('color');
if (color === '') {
document.getElementsByClassName('body-separator4')[0].style.background = favColor;
} else {
document.getElementsByClassName('body-separator4')[0].style.background = color;
}
};
document.onclick = function (y) {
if (y.target.className == 'cbtn') {
var favbgColor = y.target.style.background;
setCookie('bgcolor', favbgColor);
document.getElementsByClassName('body-separator')[0].style.background = favbgColor;
console.log(favbgColor);
}
};
window.onload = function () {
var favbgColor = document.getElementsByClassName("body-separator")[0].style.background
var bgcolor = getCookie('bgcolor');
if (bgcolor === '') {
document.getElementsByClassName('body-separator')[0].style.background = favbgColor;
} else {
document.getElementsByClassName('body-separator')[0].style.background = bgcolor;
}
};
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 this code:
var CookieHelper = function () {
return {
GetCookie : function (cookieName) {
var cookieNameRequest = cookieName + "=";
var cookiesCollection = document.cookie.split(";");
for (var i = 0; i < cookiesCollection.length; i++) {
var cookieValuePair = cookiesCollection[i];
while (cookieValuePair.charAt(0) == " ") cookieValuePair = cookieValuePair.substring(1, cookieValuePair.length);
if (cookieValuePair.indexOf(cookieNameRequest) == 0)
return cookieValuePair.substring(cookieNameRequest.length, cookieValuePair.length);
}
return null;
},
DeleteCookie : function (cookieName) {
CookieHelper.SetCookie(cookieName, "", -1);
},
SetCookie : function (cookieName, cookieValue, cookieExpirationDays) {
var tmpDate = new Date;
if (cookieExpirationDays) {
tmpDate.setTime(tmpDate.getTime() + cookieExpirationDays * 24 * 60 * 60 * 1000);
var expires = "; expires=" + tmpDate.toGMTString();
} else {
// if cookieExpirationDays isn't set cookie will expire at the end of the day
var expirationTime = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate(), 23, 59, 59);
var expires = "; expires=" + expirationTime.toGMTString();
}
document.cookie = cookieName + "=" + cookieValue + expires + "; path=/;" + (location.protocol === "https:" ? "secure=true" : "");
}
};
}();
and I need to write unit tests for GetCookie.
I tried with:
QUnit.module('Cookie Helper Tests');
QUnit.test('GetCookie - returns no cookie', function(assert) {
var stub = sinon.spy(CookieHelper, 'GetCookie');
var cookieName = 'testCookieName';
var cookieValue = CookieHelper.GetCookie(cookieName);
assert.ok(cookieValue == null, 'returns no cookie');
});
I need to mock/stub document.cookie but I am completely new with Sinon and QUnit.
Can someone give me explanation what I did wrong?
Thanks in advance!
Srdjan
Well actually you can't mock properties with Sinon and more over you cannot mock the document.cookies property as it's immutable. What you can do though, is to use a fake double object that mimics the behavior of the original object, as described here.
For example, if you were running the same test outside of the browser (e.g. in NodeJS) you would do something like that
const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');
chai.use(SinonChai);
chai.should();
context('test', function() {
it('should pass',
(done) => {
var cookieName = 'testCookieName';
document = {
cookie: cookieName + '=123'
};
var cookieValue = CookieHelper.GetCookie(cookieName);
console.log(cookieValue);
done();
});
});
in order to introduce a document object to the context and mimic it's cookies attribute by returning a fixed result.
Now, there is a workaround for the browser which involves redefining the getter and setter of 'document.cookie' as described here:
(function (document) {
var cookies = {};
document.__defineGetter__('cookie', function () {
var output = [];
for (var cookieName in cookies) {
output.push(cookieName + '=' + cookies[cookieName]);
}
return output.join(';');
});
document.__defineSetter__('cookie', function (s) {
var indexOfSeparator = s.indexOf('=');
var key = s.substr(0, indexOfSeparator);
var value = s.substring(indexOfSeparator + 1);
cookies[key] = value;
return key + '=' + value;
});
document.clearCookies = function () {
cookies = {};
};
})(document);
I am trying to do a simple IF statement to check if a specific Cookie exists:
I'm not looking to over complicate anything just something simple like
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
What is this syntax for this?
first:
function getCookie(name) {
var cookies = '; ' + document.cookie;
var splitCookie = cookies.split('; ' + name + '=');
if (splitCookie.lenght == 2) return splitCookie.pop();
}
then you can use your if statement:
if (getCookie('a'))
console.log("false");
else
console.log("true");
should have work.
Maybe this can help (w3schools documentation about javascript cookies) :
https://www.w3schools.com/js/js_cookies.asp
At A Function to Get a Cookie
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 "";
}
this could help you:
class Cookies {
static exists(name) {
return name && !!Cookies.get(name);
}
static set(name, value, expires = Date.now() + 8.64e+7, path = '/') {
document.cookie = `${name}=${value};expires=${expires};path=${path};`;
}
static get(name = null) {
const cookies = decodeURIComponent(document.cookie)
.split(/;\s?/)
.map(c => {
let [name, value] = c.split(/\s?=\s?/);
return {name, value};
})
;
return name
? cookies.filter(c => c.name === name).pop() || null
: cookies
;
}
}
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.