replaced navigator with the angularjs equivalent .navigator, made the function browserSupportsCookies available for public access as cookie.isSupported and wrote tests to verify the functionality

master
Arthur Helmel 10 years ago
parent dbd1913d9a
commit 8223e647c9

@ -1,6 +1,6 @@
/** /**
* An Angular module that gives you access to the browsers local storage * An Angular module that gives you access to the browsers local storage
* @version v0.1.3 - 2014-10-14 * @version v0.1.3 - 2014-10-30
* @link https://github.com/grevory/angular-local-storage * @link https://github.com/grevory/angular-local-storage
* @author grevory <greg@gregpike.ca> * @author grevory <greg@gregpike.ca>
* @license MIT License, http://www.opensource.org/licenses/MIT * @license MIT License, http://www.opensource.org/licenses/MIT
@ -286,16 +286,16 @@ angularLocalStorage.provider('localStorageService', function() {
}; };
// Checks the browser to see if cookies are supported // Checks the browser to see if cookies are supported
var browserSupportsCookies = function() { var browserSupportsCookies = (function() {
try { try {
return navigator.cookieEnabled || return $window.navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 || ("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1)); ($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) { } catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message); $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false; return false;
} }
}; }());
// Directly adds a value to cookies // Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser // Typically used as a fallback is local storage is not available in the browser
@ -308,7 +308,7 @@ angularLocalStorage.provider('localStorageService', function() {
value = toJson(value); value = toJson(value);
} }
if (!browserSupportsCookies()) { if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false; return false;
} }
@ -344,7 +344,7 @@ angularLocalStorage.provider('localStorageService', function() {
// Directly get a value from a cookie // Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular' // Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) { var getFromCookies = function (key) {
if (!browserSupportsCookies()) { if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false; return false;
} }
@ -437,6 +437,7 @@ angularLocalStorage.provider('localStorageService', function() {
deriveKey: deriveQualifiedKey, deriveKey: deriveQualifiedKey,
length: lengthOfLocalStorage, length: lengthOfLocalStorage,
cookie: { cookie: {
isSupported: browserSupportsCookies,
set: addToCookies, set: addToCookies,
add: addToCookies, //DEPRECATED add: addToCookies, //DEPRECATED
get: getFromCookies, get: getFromCookies,

@ -1,7 +1,7 @@
/** /**
* An Angular module that gives you access to the browsers local storage * An Angular module that gives you access to the browsers local storage
* @version v0.1.3 - 2014-10-14 * @version v0.1.3 - 2014-10-30
* @link https://github.com/grevory/angular-local-storage * @link https://github.com/grevory/angular-local-storage
* @author grevory <greg@gregpike.ca> * @author grevory <greg@gregpike.ca>
* @license MIT License, http://www.opensource.org/licenses/MIT * @license MIT License, http://www.opensource.org/licenses/MIT
*/!function(a,b){"use strict";function c(a){return/^-?\d+\.?\d*$/.test(a.replace(/["']/g,""))}var d=b.isDefined,e=b.isUndefined,f=b.isNumber,g=b.isObject,h=b.isArray,i=b.extend,j=b.toJson,k=b.fromJson,l=b.module("LocalStorageModule",[]);l.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){this.prefix=a},this.setStorageType=function(a){this.storageType=a},this.setStorageCookie=function(a,b){this.cookie={expiry:a,path:b}},this.setStorageCookieDomain=function(a){this.cookie.domain=a},this.setNotify=function(a,b){this.notify={setItem:a,removeItem:b}},this.$get=["$rootScope","$window","$document","$parse",function(a,b,l,m){var n,o=this,p=o.prefix,q=o.cookie,r=o.notify,s=o.storageType;l?l[0]&&(l=l[0]):l=document,"."!==p.substr(-1)&&(p=p?p+".":"");var t=function(a){return p+a},u=function(){try{var c=s in b&&null!==b[s],d=t("__"+Math.round(1e7*Math.random()));return c&&(n=b[s],n.setItem(d,""),n.removeItem(d)),c}catch(e){return s="cookie",a.$broadcast("LocalStorageModule.notification.error",e.message),!1}}(),v=function(b,c){if(e(c)?c=null:(g(c)||h(c)||f(+c||c))&&(c=j(c)),!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:"cookie"}),B(b,c);try{(g(c)||h(c))&&(c=j(c)),n&&n.setItem(t(b),c),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:o.storageType})}catch(d){return a.$broadcast("LocalStorageModule.notification.error",d.message),B(b,c)}return!0},w=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),C(b);var d=n?n.getItem(t(b)):null;return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)||c(d)?k(d):d:null},x=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),D(b);try{n.removeItem(t(b)),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:o.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),D(b)}return!0},y=function(){if(!u)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=p.length,c=[];for(var d in n)if(d.substr(0,b)===p)try{c.push(d.substr(b))}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.Description),[]}return c},z=function(b){b=b||"";var c=p.slice(0,-1),d=new RegExp(c+"."+b);if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),E();var e=p.length;for(var f in n)if(d.test(f))try{x(f.substr(e))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),E()}return!0},A=function(){try{return navigator.cookieEnabled||"cookie"in l&&(l.cookie.length>0||(l.cookie="test").indexOf.call(l.cookie,"test")>-1)}catch(b){return a.$broadcast("LocalStorageModule.notification.error",b.message),!1}},B=function(b,c){if(e(c))return!1;if((h(c)||g(c))&&(c=j(c)),!A())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var d="",f=new Date,i="";if(null===c?(f.setTime(f.getTime()+-864e5),d="; expires="+f.toGMTString(),c=""):0!==q.expiry&&(f.setTime(f.getTime()+24*q.expiry*60*60*1e3),d="; expires="+f.toGMTString()),b){var k="; path="+q.path;q.domain&&(i="; domain="+q.domain),l.cookie=t(b)+"="+encodeURIComponent(c)+d+k+i}}catch(m){return a.$broadcast("LocalStorageModule.notification.error",m.message),!1}return!0},C=function(b){if(!A())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var c=l.cookie&&l.cookie.split(";")||[],d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t(b)+"=")){var f=decodeURIComponent(e.substring(p.length+b.length+1,e.length));try{var g=JSON.parse(f);return k(g)}catch(h){return f}}}return null},D=function(a){B(a,null)},E=function(){for(var a=null,b=p.length,c=l.cookie.split(";"),d=0;d<c.length;d++){for(a=c[d];" "===a.charAt(0);)a=a.substring(1,a.length);var e=a.substring(b,a.indexOf("="));D(e)}},F=function(){return s},G=function(a,b,c,e){e=e||b;var f=w(e);return null===f&&d(c)?f=c:g(f)&&g(c)&&(f=i(c,f)),m(b).assign(a,f),a.$watch(b,function(a){v(e,a)},g(a[b]))},H=function(){for(var a=0,c=b[s],d=0;d<c.length;d++)0===c.key(d).indexOf(p)&&a++;return a};return{isSupported:u,getStorageType:F,set:v,add:v,get:w,keys:y,remove:x,clearAll:z,bind:G,deriveKey:t,length:H,cookie:{set:B,add:B,get:C,remove:D,clearAll:E}}}]})}(window,window.angular); */!function(a,b){"use strict";function c(a){return/^-?\d+\.?\d*$/.test(a.replace(/["']/g,""))}var d=b.isDefined,e=b.isUndefined,f=b.isNumber,g=b.isObject,h=b.isArray,i=b.extend,j=b.toJson,k=b.fromJson,l=b.module("LocalStorageModule",[]);l.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){this.prefix=a},this.setStorageType=function(a){this.storageType=a},this.setStorageCookie=function(a,b){this.cookie={expiry:a,path:b}},this.setStorageCookieDomain=function(a){this.cookie.domain=a},this.setNotify=function(a,b){this.notify={setItem:a,removeItem:b}},this.$get=["$rootScope","$window","$document","$parse",function(a,b,l,m){var n,o=this,p=o.prefix,q=o.cookie,r=o.notify,s=o.storageType;l?l[0]&&(l=l[0]):l=document,"."!==p.substr(-1)&&(p=p?p+".":"");var t=function(a){return p+a},u=function(){try{var c=s in b&&null!==b[s],d=t("__"+Math.round(1e7*Math.random()));return c&&(n=b[s],n.setItem(d,""),n.removeItem(d)),c}catch(e){return s="cookie",a.$broadcast("LocalStorageModule.notification.error",e.message),!1}}(),v=function(b,c){if(e(c)?c=null:(g(c)||h(c)||f(+c||c))&&(c=j(c)),!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:"cookie"}),B(b,c);try{(g(c)||h(c))&&(c=j(c)),n&&n.setItem(t(b),c),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:o.storageType})}catch(d){return a.$broadcast("LocalStorageModule.notification.error",d.message),B(b,c)}return!0},w=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),C(b);var d=n?n.getItem(t(b)):null;return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)||c(d)?k(d):d:null},x=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),D(b);try{n.removeItem(t(b)),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:o.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),D(b)}return!0},y=function(){if(!u)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=p.length,c=[];for(var d in n)if(d.substr(0,b)===p)try{c.push(d.substr(b))}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.Description),[]}return c},z=function(b){b=b||"";var c=p.slice(0,-1),d=new RegExp(c+"."+b);if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),E();var e=p.length;for(var f in n)if(d.test(f))try{x(f.substr(e))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),E()}return!0},A=function(){try{return b.navigator.cookieEnabled||"cookie"in l&&(l.cookie.length>0||(l.cookie="test").indexOf.call(l.cookie,"test")>-1)}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),!1}}(),B=function(b,c){if(e(c))return!1;if((h(c)||g(c))&&(c=j(c)),!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var d="",f=new Date,i="";if(null===c?(f.setTime(f.getTime()+-864e5),d="; expires="+f.toGMTString(),c=""):0!==q.expiry&&(f.setTime(f.getTime()+24*q.expiry*60*60*1e3),d="; expires="+f.toGMTString()),b){var k="; path="+q.path;q.domain&&(i="; domain="+q.domain),l.cookie=t(b)+"="+encodeURIComponent(c)+d+k+i}}catch(m){return a.$broadcast("LocalStorageModule.notification.error",m.message),!1}return!0},C=function(b){if(!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var c=l.cookie&&l.cookie.split(";")||[],d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t(b)+"=")){var f=decodeURIComponent(e.substring(p.length+b.length+1,e.length));try{var g=JSON.parse(f);return k(g)}catch(h){return f}}}return null},D=function(a){B(a,null)},E=function(){for(var a=null,b=p.length,c=l.cookie.split(";"),d=0;d<c.length;d++){for(a=c[d];" "===a.charAt(0);)a=a.substring(1,a.length);var e=a.substring(b,a.indexOf("="));D(e)}},F=function(){return s},G=function(a,b,c,e){e=e||b;var f=w(e);return null===f&&d(c)?f=c:g(f)&&g(c)&&(f=i(c,f)),m(b).assign(a,f),a.$watch(b,function(a){v(e,a)},g(a[b]))},H=function(){for(var a=0,c=b[s],d=0;d<c.length;d++)0===c.key(d).indexOf(p)&&a++;return a};return{isSupported:u,getStorageType:F,set:v,add:v,get:w,keys:y,remove:x,clearAll:z,bind:G,deriveKey:t,length:H,cookie:{isSupported:A,set:B,add:B,get:C,remove:D,clearAll:E}}}]})}(window,window.angular);

@ -259,16 +259,16 @@ angularLocalStorage.provider('localStorageService', function() {
}; };
// Checks the browser to see if cookies are supported // Checks the browser to see if cookies are supported
var browserSupportsCookies = function() { var browserSupportsCookies = (function() {
try { try {
return navigator.cookieEnabled || return $window.navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 || ("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1)); ($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) { } catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message); $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false; return false;
} }
}; }());
// Directly adds a value to cookies // Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser // Typically used as a fallback is local storage is not available in the browser
@ -281,7 +281,7 @@ angularLocalStorage.provider('localStorageService', function() {
value = toJson(value); value = toJson(value);
} }
if (!browserSupportsCookies()) { if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false; return false;
} }
@ -317,7 +317,7 @@ angularLocalStorage.provider('localStorageService', function() {
// Directly get a value from a cookie // Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular' // Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) { var getFromCookies = function (key) {
if (!browserSupportsCookies()) { if (!browserSupportsCookies) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED'); $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false; return false;
} }
@ -410,6 +410,7 @@ angularLocalStorage.provider('localStorageService', function() {
deriveKey: deriveQualifiedKey, deriveKey: deriveQualifiedKey,
length: lengthOfLocalStorage, length: lengthOfLocalStorage,
cookie: { cookie: {
isSupported: browserSupportsCookies,
set: addToCookies, set: addToCookies,
add: addToCookies, //DEPRECATED add: addToCookies, //DEPRECATED
get: getFromCookies, get: getFromCookies,

@ -62,6 +62,12 @@ describe('localStorageService', function() {
}; };
} }
function expectCookieSupporting(expected) {
return function(localStorageService) {
expect(localStorageService.cookie.isSupported).toEqual(expected);
};
}
function expectDomain(domain) { function expectDomain(domain) {
return function($document, localStorageService) { return function($document, localStorageService) {
localStorageService.set('foo','bar'); //Should trigger first time localStorageService.set('foo','bar'); //Should trigger first time
@ -417,7 +423,10 @@ describe('localStorageService', function() {
beforeEach(module('LocalStorageModule', function($provide) { beforeEach(module('LocalStorageModule', function($provide) {
$provide.value('$window', { $provide.value('$window', {
localStorage: false, localStorage: false,
sessionStorage: false sessionStorage: false,
navigator: {
cookieEnabled: true
}
}); });
$provide.value('$document', { $provide.value('$document', {
cookie: '' cookie: ''
@ -428,6 +437,10 @@ describe('localStorageService', function() {
expectSupporting(false) expectSupporting(false)
)); ));
it('cookie.isSupported should be true if cookies are enabled', inject(
expectCookieSupporting(true)
));
it('fallback storage type should be cookie', inject( it('fallback storage type should be cookie', inject(
expectStorageTyping('cookie') expectStorageTyping('cookie')
)); ));
@ -504,4 +517,22 @@ describe('localStorageService', function() {
}; };
}); });
//cookie disabled
describe('No Cookie', function() {
beforeEach(module('LocalStorageModule', function($provide) {
$provide.value('$window', {
navigator: {
cookieEnabled: false
}
});
$provide.value('$document', {
});
}));
it('cookie.isSupported should be false if cookies are disabled', inject(
expectCookieSupporting(false)
));
});
}); });