Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*!( rvklein.me -- cookiestorage.js -- [ Older stuff, could improve in various ways. ] )!*/
- /* Create an interface to cookies similar to the LocalStorage API. */
- var cookieStorage = new function(){
- function getItem( n ){
- var c = document.cookie.split( '; ' ) ;
- var tmp ;
- for( var j = c.length , i = 0 ; i < j ; i++ ){
- tmp = c[ i ].split( '=' ) ;
- if( tmp[ 1 ] ){
- return( tmp[ 1 ] );
- }else{
- return( null );
- }
- }
- }
- function setItem( n , v , flags ){
- if( !n || !v ){ return( false ); }
- if( typeof( v ) !== 'string' ){
- if( typeof( v ) === 'number' ){
- if( v == 0 || !( v % 1 ) ){
- v = parseInt( v , 10 ) ;
- }else{
- v = parseFloat( v , 10 ) ;
- }
- }else{
- v = JSON.stringify( v ) ;
- }
- }
- var out = ( n + '=' + encodeURIComponent( v ) ) ;
- if( flags ){
- if( flags.expires ){
- if( flags.expires.constructor.name === 'Date' ){
- flags.expires = flags.expires.toGMTString() ;
- }
- out += ( '; Expires=' + flags.expires ) ;
- }
- if( flags.secure ){ out += ( '; Secure' ) ; }
- if( flags.domain ){ out += ( '; Domain=' + flags.domain ) ; }
- if( flags.path ){ out += ( '; Path=' + flags.path ) ; }
- }
- document.cookie = out ;
- }
- function removeItem( n ){
- document.cookie = ( n + '=' + '; Expires='
- + 'Thu, 01 Jan 1970 00:00:00 GMT'
- ) ;
- }
- this.getItem = getItem ;
- this.setItem = setItem ;
- this.removeItem = removeItem ;
- } ;
- /*!(
- The most notable ways to improve this include:
- * setting a reasonable lower quota limit or probing for upper cookie storage limits and throwing an error when trying to assign above quota, like the LocalStorage/SessionStorage APIs
- * checking to see if window.navigator.cookieEnabled equals true before writing, throw an error when trying to use cookieStorage if cookieEnabled is false. We treat it as though it were a disabled permission, as it is.
- * I would probably not format my code like this any more.
- )!*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement