From 8d476f585ab6fda7384ac1f7faff634dd8fde28a Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Fri, 6 Jan 2012 20:19:38 -0500 Subject: [PATCH 01/29] lame, but deleting old files --- README.md | 80 ------------- demo.html | 19 ---- pack.sh | 3 - session.js | 302 ------------------------------------------------- session.min.js | 8 -- 5 files changed, 412 deletions(-) delete mode 100644 README.md delete mode 100644 demo.html delete mode 100755 pack.sh delete mode 100644 session.js delete mode 100644 session.min.js diff --git a/README.md b/README.md deleted file mode 100644 index 2ce477a..0000000 --- a/README.md +++ /dev/null @@ -1,80 +0,0 @@ -Session.js -== - -Gives information about the current session. - -To use: include the file session.js, then access the visitor object. -It uses the google javascript loader to get location data. -For async loading, use the window.session_loaded callback. - -To add more fields, add or remove included modules and options near the bottom of the js file. - - -API demo dump of `window.session`: -
-  {
-    "api_version": 0.2,
-    "locale": {
-      "country": "US",
-      "lang": "en"
-    },
-    "cur_session": {
-      "visits": 1,
-      "search": {
-        "engine": null,
-        "query": null
-      },
-      "referrer": "",
-      "url": "http://localhost:8000/demo.html",
-      "path": "/demo.html",
-      "start": 1325893718929,
-      "last_visit": 1325893718929
-    },
-    "orig_session": {
-      "visits": 20,
-      "search": {
-        "engine": null,
-        "query": null
-      },
-      "referrer": "http://localhost:8000/",
-      "url": "http://localhost:8000/test_visitor.html",
-      "path": "/test_visitor.html",
-      "start": 1325886709703,
-      "last_visit": 1325893718932
-    },
-    "browser": {
-      "browser": "Chrome",
-      "version": 16,
-      "OS": "Mac"
-    },
-    "plugins": {
-      "flash": true,
-      "silverlight": true,
-      "java": true,
-      "quicktime": true
-    },
-    "device": {
-      "screen": {
-        "width": 1280,
-        "height": 1024
-      },
-      "viewport": {
-        "width": 1206,
-        "height": 816
-      },
-      "is_phone": false,
-      "is_tablet": false,
-      "is_mobile": false
-    },
-    "location": {
-      "latitude": 35.046,
-      "longitude": -85.31,
-      "address": {
-        "city": "Chattanooga",
-        "region": "TN",
-        "country": "USA",
-        "country_code": "US"
-      }
-    }
-  }
-
diff --git a/demo.html b/demo.html deleted file mode 100644 index 9f484c7..0000000 --- a/demo.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - -

Session.js demo

-

Demo output:

-
-  
-  
- - - - diff --git a/pack.sh b/pack.sh deleted file mode 100755 index e43c0ce..0000000 --- a/pack.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -echo 'Packing session.js to session.min.js' -uglifyjs session.js > session.min.js diff --git a/session.js b/session.js deleted file mode 100644 index 72c1035..0000000 --- a/session.js +++ /dev/null @@ -1,302 +0,0 @@ -/** - * session.js 0.0.2 - * (c) 2012 Iain, CodeJoust - * session is freely distributable under the MIT license. - * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. - * This version uses google's jsapi library for location services. - * For details, see: https://github.com/codejoust/session.js - */ -(function(win, doc){ - var opts = { - enable_location: true, - session_days: 32 - } - if ('session_opts' in window){ opts = session_opts; } - var BrowserDetect = { // from quirksmode.org/js/detect.html - detect_browser: function () { - return {browser: this.searchString(this.dataBrowser), - version: this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion), - OS: this.searchString(this.dataOS)}; - }, - searchString: function (data) { - for (var i=0;i0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Fri, 6 Jan 2012 20:20:02 -0500 Subject: [PATCH 02/29] adding demo for gh_pages --- index.html | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 index.html diff --git a/index.html b/index.html new file mode 100644 index 0000000..9f484c7 --- /dev/null +++ b/index.html @@ -0,0 +1,19 @@ + + + + + +

Session.js demo

+

Demo output:

+
+  
+  
+ + + + From e324a892d8fde6eaea97b0f31001d3b6ddf82414 Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Fri, 6 Jan 2012 20:23:11 -0500 Subject: [PATCH 03/29] adding js file for demo --- session.js | 302 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 session.js diff --git a/session.js b/session.js new file mode 100644 index 0000000..72c1035 --- /dev/null +++ b/session.js @@ -0,0 +1,302 @@ +/** + * session.js 0.0.2 + * (c) 2012 Iain, CodeJoust + * session is freely distributable under the MIT license. + * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. + * This version uses google's jsapi library for location services. + * For details, see: https://github.com/codejoust/session.js + */ +(function(win, doc){ + var opts = { + enable_location: true, + session_days: 32 + } + if ('session_opts' in window){ opts = session_opts; } + var BrowserDetect = { // from quirksmode.org/js/detect.html + detect_browser: function () { + return {browser: this.searchString(this.dataBrowser), + version: this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion), + OS: this.searchString(this.dataOS)}; + }, + searchString: function (data) { + for (var i=0;i Date: Sat, 7 Jan 2012 01:15:18 -0500 Subject: [PATCH 04/29] Updating demo --- session.js | 139 +++++++++++++++++++++++++++++++------------------ session.min.js | 8 +++ 2 files changed, 97 insertions(+), 50 deletions(-) create mode 100644 session.min.js diff --git a/session.js b/session.js index 72c1035..6cdff5b 100644 --- a/session.js +++ b/session.js @@ -8,10 +8,28 @@ */ (function(win, doc){ var opts = { - enable_location: true, - session_days: 32 + use_html5_location: false, + // use html5 location -- this _ONLY_ return lat/long, not an city/address + ipinfodb_key: null, + // attempts to use ipinfodb if provided a valid key -- get a key at http://ipinfodb.com/register.php + gapi_location: true, + // leaving true allows for fallback for both the html5 location and the ipinfodb + session_days: 32, + // how many days session information is kept in a cookie + location_cookie_name: 'location', + // the name of the location cookie + // -- warning: different providers use the same cookie + // -- if switching providers, remember to use another cookie or provide checks for old cookies + session_cookie_name: 'first_session', + // session cookie name + location_cookie_hours: 2 + // lifetime of the location cookie + } + if ('session_opts' in win){ + for (opt in win.session_opts){ + opts[opt] = win.session_opts[opt]; + } } - if ('session_opts' in window){ opts = session_opts; } var BrowserDetect = { // from quirksmode.org/js/detect.html detect_browser: function () { return {browser: this.searchString(this.dataBrowser), @@ -81,8 +99,7 @@ return p; }), set_cookie: function(c_name, value, expire) { - var exdate=new Date(); - exdate.setDate(exdate.getDate()+expire); + var exdate = new Date(); exdate.setDate(exdate.getDate()+expire); document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString()); }, get_cookie: function(c_name) { @@ -137,43 +154,15 @@ return result; }, is_undef: function(obj){ return obj === void 0; }, // from underscore.js - try_obj: function(tries, obj){ - for (var i = 0; i < tries.length; i++){ - obj_try = obj[tries[i]]; - if (!utils.is_undef(obj_try) && obj_try != null && obj_try != ''){ - return obj_try; - } - } - return null; - }, - try_props: function(props){ - for(var i = 0; i < props.length; i++){ - if (!utils.is_undef(props[i]) && props[i] != null && props[i] != ''){ - return props[i]; - } - } + embed_script: function(url){ + var scr = document.createElement('script'); + scr.type = 'text/javascript'; + scr.src = url; + document.getElementsByTagName('head')[0].appendChild(scr); } }; - + var modules = { - location: function(cookie_name){ - var embed_script = function(url){ - var scr = document.createElement('script'); - scr.type = 'text/javascript'; - scr.src = url; - document.getElementsByTagName('head')[0].appendChild(scr); - } - return function(cb){ - var loc = null; - if (!utils.get_cookie(cookie_name)){ - win.gloader_loaded = function() { - if ('google' in window) { - cb(win.google.loader.ClientLocation); - utils.set_cookie(cookie_name,utils.stringify_json(win.google.loader.ClientLocation), 1000 * 60 * 60 * 2);} } - embed_script('https://www.google.com/jsapi?callback=gloader_loaded'); - } else { cb(utils.parse_json(utils.get_cookie(cookie_name))); } - } - }, locale: function(){ var res = utils.search(['language', 'browserLanguage', 'systemLanguage', 'userLanguage'], function(prop_name){ return navigator[prop_name]; @@ -190,8 +179,8 @@ var elem=doc.documentElement, doc_body=doc.getElementsByTagName('body')[0], agent = navigator.userAgent; device.viewport.width=(win.innerWidth||elem.clientWidth||doc_body.clientWidth); device.viewport.height=(win.innerHeight||elem.clientHeight||doc_body.clientHeight); - device.is_phone = !!(agent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i)); device.is_tablet = !!(agent.match(/(iPad|SCH-I800|xoom|kindle)/i)); + device.is_phone = !device.is_tablet && !!(agent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i)); device.is_mobile = device.is_tablet || device.is_phone; return device; }, @@ -201,10 +190,7 @@ return !!utils.find(navigator.plugins, function(plugin){ if (plugin && plugin['name'] && plugin['name'].toLowerCase().indexOf(plugin_name) !== -1){ return true; - } - }); - } - } + } }); } } return { flash: check_plugin('flash'), silverlight: check_plugin('silverlight'), @@ -253,23 +239,75 @@ utils.set_cookie(cookie_name, JSON.stringify(sess), expires) } return sess; + }, + html5_location: function(){ + return function(cb){ + navigator.geolocation.getCurrentPosition(function(position){ + position['source'] = 'html5'; + return position + }, function(err_msg){ + if (opts.gapi_location){ modules.gapi_location()(cb); } + else { cb({err: true, source: 'html5'}); } + }); + + } + }, + gapi_location: function(){ + return function(cb){ + var loc = null; + if (!utils.get_cookie(opts.location_cookie_name)){ + win.gloader_loaded = function(){ + if ('google' in window) { + if (win.google.loader.ClientLocation){ + win.google.loader.ClientLocation.source = 'google'; + cb(win.google.loader.ClientLocation); + } else { + cb({err: true, source: 'google'}) + } + utils.set_cookie(opts.location_cookie_name,utils.stringify_json(win.google.loader.ClientLocation), 1000 * 60 * 60 * opts.location_cookie_hours);} } + utils.embed_script('https://www.google.com/jsapi?callback=gloader_loaded'); + } else { cb(utils.parse_json(utils.get_cookie(opts.location_cookie_name))); } + } + }, + ipinfodb_location: function(api_key){ + return function(cb){ + var loc_cookie = utils.get_cookie(opts.location_cookie_name); + if (loc_cookie){ return cb(JSON.parse(loc_cookie)); } + win.ipinfocb = function(data){ + if (data['statusCode'] == 'OK'){ + data['source'] = 'ipinfodb'; + utils.set_cookie(opts.location_cookie_name, JSON.stringify(data), 1000 * 60 * 60 * opts.location_cookie_hours); + cb(data); + } else { + if (opts.gapi_location){ + return modules.gapi()(cb); + } else { cb({err: true, source: 'ipinfodb'}); } + } + } + utils.embed_script('http://api.ipinfodb.com/v3/ip-city/?key='+ api_key +'&format=json&callback=ipinfocb'); + } } } var session_loader = { modules: { locale: modules.locale(), cur_session: modules.session(), - orig_session: modules.session('first_session', 1000 * 60 * 60 * 24 * (opts.session_days || 32)), + orig_session: modules.session(opts.session_cookie_name, 1000 * 60 * 60 * 24 * opts.session_days), browser: modules.browser(), plugins: modules.plugins(), device: modules.device() }, init: function(){ - if (opts.enable_location){ - session_loader.modules['location'] = modules.location('location'); + // location switch + if (opts.use_html5_location){ + session_loader.modules['location'] = modules.html5_location(); + } else if (opts.ipinfodb_key){ + session_loader.modules['location'] = modules.ipinfodb_location(opts.ipinfodb_key); + } else if (opts.gapi_location){ + session_loader.modules['location'] = modules.gapi_location(); } // Setup session Object - var asyncs = 0, check_async = function(){ + var asyncs = 0, check_async = function(){; if (asyncs == 0){ win.session_loaded && win.session_loaded(win.session); } }; win.modules = session_loader.modules; @@ -278,7 +316,7 @@ (function(module_name){ var module_runner = session_loader.modules[module_name]; if (typeof(module_runner) === 'function'){ - //try { + try { var ret = module_runner; if (typeof(ret) === 'function'){ asyncs++; @@ -290,12 +328,13 @@ } else { win.session[module_name] = ret; } - //} catch (e) { if (typeof(console) !== 'undefined'){ console.log(e); } } + } catch (e) { if (typeof(console) !== 'undefined'){ console.log(e); } } } else { win.session[module_name] = module_runner; } })(module_name); } + check_async(); } }; session_loader.init(); diff --git a/session.min.js b/session.min.js new file mode 100644 index 0000000..432b831 --- /dev/null +++ b/session.min.js @@ -0,0 +1,8 @@ +/** + * session.js 0.0.2 + * (c) 2012 Iain, CodeJoust + * session is freely distributable under the MIT license. + * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. + * This version uses google's jsapi library for location services. + * For details, see: https://github.com/codejoust/session.js + */(function(win,doc){var opts={use_html5_location:!1,ipinfodb_key:null,gapi_location:!0,session_days:32,location_cookie_name:"location",session_cookie_name:"first_session",location_cookie_hours:2};if("session_opts"in win)for(opt in win.session_opts)opts[opt]=win.session_opts[opt];var BrowserDetect={detect_browser:function(){return{browser:this.searchString(this.dataBrowser),version:this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion),OS:this.searchString(this.dataOS)}},searchString:function(a){for(var b=0;b0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Sat, 7 Jan 2012 10:06:39 -0500 Subject: [PATCH 05/29] updating demo, adding syntax hilighting --- index.html | 137 +++++++++++++++++++++++++++++++++++++++++++++++-- session.js | 102 ++++++++++++++++++------------------ session.min.js | 2 +- 3 files changed, 185 insertions(+), 56 deletions(-) diff --git a/index.html b/index.html index 9f484c7..8974229 100644 --- a/index.html +++ b/index.html @@ -1,16 +1,147 @@ + Demo for Session.js + -

Session.js demo

+

Session.js Demo Page

Demo output:

-  
+    loading...
   
+ +

Session.JS on GitHub by Iain

diff --git a/session.js b/session.js index 6cdff5b..0eac793 100644 --- a/session.js +++ b/session.js @@ -31,52 +31,50 @@ } } var BrowserDetect = { // from quirksmode.org/js/detect.html - detect_browser: function () { - return {browser: this.searchString(this.dataBrowser), - version: this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion), - OS: this.searchString(this.dataOS)}; - }, - searchString: function (data) { - for (var i=0;i0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Sat, 7 Jan 2012 10:26:28 -0500 Subject: [PATCH 06/29] adding ipinfodb demo --- ipinfodb_demo.html | 158 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 ipinfodb_demo.html diff --git a/ipinfodb_demo.html b/ipinfodb_demo.html new file mode 100644 index 0000000..9bf2710 --- /dev/null +++ b/ipinfodb_demo.html @@ -0,0 +1,158 @@ + + + Demo for Session.js + + + + +

Session.js Demo Page

+

Using ipinfodb for location lookup

+

Demo output:

+
+    loading...
+  
+ +

Session.JS on GitHub by Iain

+ + + + From bb780329c78c20ef2362ee7372ded6df590da0b1 Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Sat, 7 Jan 2012 10:27:28 -0500 Subject: [PATCH 07/29] Changing cookie name to prevent conflicts --- ipinfodb_demo.html | 1 + 1 file changed, 1 insertion(+) diff --git a/ipinfodb_demo.html b/ipinfodb_demo.html index 9bf2710..c5cb30a 100644 --- a/ipinfodb_demo.html +++ b/ipinfodb_demo.html @@ -148,6 +148,7 @@

Using ipinfodb for location lookup

enable_location: true, // use google as a fallback from ipinfodb session_days: 5, + location_cookie_name: 'location_ipinfodb', // keep session information for five days. ipinfodb_key: '6be6b77938ee03bc2c08cf03cb82d4e1f270b84415ac013e7ec728f11d24be67' // demo for ipinfodb. PLEASE USE YOUR OWN API KEY. (register for free at ipinfodb.com/) From d78e3ac12ee0024f588f539f4bbc3aab37f00bff Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Sat, 7 Jan 2012 11:31:29 -0500 Subject: [PATCH 08/29] Updating demo files --- session.js | 73 ++++++++++++++++++++++++++++---------------------- session.min.js | 4 +-- 2 files changed, 43 insertions(+), 34 deletions(-) diff --git a/session.js b/session.js index 0eac793..3ef90ba 100644 --- a/session.js +++ b/session.js @@ -1,5 +1,5 @@ /** - * session.js 0.0.2 + * session.js 0.2 * (c) 2012 Iain, CodeJoust * session is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. @@ -10,8 +10,8 @@ var opts = { use_html5_location: false, // use html5 location -- this _ONLY_ return lat/long, not an city/address - ipinfodb_key: null, - // attempts to use ipinfodb if provided a valid key -- get a key at http://ipinfodb.com/register.php + ipinfodb_key: false, + // attempts to use ipinfodb if provided an API key -- get a key at http://ipinfodb.com/register.php gapi_location: true, // leaving true allows for fallback for both the html5 location and the ipinfodb session_days: 32, @@ -53,30 +53,41 @@ return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); }, dataBrowser: [ - { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, - { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, + { string: navigator.userAgent,subString: "Chrome", identity: "Chrome" }, + { string: navigator.userAgent,subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version"}, { prop: win.opera, identity: "Opera", versionSearch: "Version" }, { string: navigator.vendor, subString: "iCab",identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, - { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, - { string: navigator.vendor, subString: "Camino", identity: "Camino" }, + { string: navigator.userAgent,subString: "Firefox", identity: "Firefox" }, + { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, - { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, - { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, + { string: navigator.userAgent,subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, + { string: navigator.userAgent,subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ - { string: navigator.platform, subString: "Win", identity: "Windows"}, + { string: navigator.platform, subString: "Win", identity: "Windows"}, { string: navigator.platform, subString: "Mac", identity: "Mac" }, - { string: navigator.userAgent,subString: "iPhone", identity: "iPhone/iPod" }, - { string: navigator.userAgent,subString: 'iPad', identitiy: 'iPad'}, + { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, + { string: navigator.userAgent, subString: 'iPad', identitiy: 'iPad'}, { string: navigator.platform, subString: "Linux", identity: "Linux" }, { string: navigator.userAgent, subString: 'Android', identity: 'Android'}] }; - var utils = { + var utils = window.utils = { + parse_url: function(url_str){ + var el = document.createElement('a'); el.href = url_str; + var qs = {}; + if (el.search.substr(1) != ''){ + utils.each(el.search.substr(1).split('&'), function(part){ + var parts = part.split('='); + if (parts.length == 2){ qs[parts[0]] = decodeURI(parts[1]); } + }); + } + return {host: el.host, path: el.pathname, protocol: el.protocol, port: el.port, search: el.search, qs: qs}; + }, stringify_json: JSON.stringify || function (obj) { var t = typeof (obj); if (t != "object" || obj === null) { @@ -199,16 +210,20 @@ session: function(cookie_name, expires){ if (cookie_name){ var sess = utils.get_cookie(cookie_name); } if (!sess){ - sess = {visits: 1, search: {engine: null, query: null}} - var engines = [{nm: 'Google', url: "https?://(?:www\.)?(?:images.)?google.(?:com|[a-z]{2}|com?.[a-z]{2})", query: 'q'}, - {nm: "Bing", url: "https?://(?:www\.)?bing.com", query: "q"}, - {nm: "Yahoo", url:"https?://(?:www\.)?(?:.+.)?search.yahoo.(?:com|[a-z]{2}|com?.[a-z]{2})", query: "p"}, - {nm: "AOL", url:"https?://(?:www\.)?(?:aol)?search.aol.(?:com|[a-z]{2}|com?.[a-z]{2})", query: "q"}, - {nm: "Ask", url:"https?://(?:www\.)?(?:[a-z]+.)?ask.com", query:"q"}, - {nm: "Baidu", url:"https?://(?:www\.)?baidu.com", query:"wd"}]; + var sess = { + visits: 1, referrer: doc.referrer, referrer_info: utils.parse_url(doc.referrer), + url: win.location.href, path: win.location.pathname, + start: (new Date()).getTime(), last_visit: (new Date()).getTime(), + search: {engine: null, query: null}}, engines = [ + {nm: 'Google', host: "google", query: 'q'}, + {nm: "Bing", host: "bing.com", query: "q"}, + {nm: "Yahoo", host:"search.yahoo", query: "p"}, + {nm: "AOL", host:"search.aol", query: "q"}, + {nm: "Ask", host:"ask.com", query:"q"}, + {nm: "Baidu", host:"baidu.com", query:"wd"}, + ]; utils.find(engines, function(engine){ - var res = RegExp(engine['url'] + '/.*[?&]' + engine.query + '=([^&]+)').exec(doc.referrer); - if (res){ + if (sess.referrer_info.host.indexOf(engine.host) != -1 && sess.referrer_info.qs[engine.query]){ sess.search.engine = engine.nm; sess.search.query = engine.query; return true; @@ -216,19 +231,13 @@ }); if (!sess.search.engine){ utils.find(['q','query','term','p','wd','query','text'], function(query_term){ - var res = RegExp("[?&]" + query_term + "=([^&]+)").exec(doc.referrer); - if (res){ + if (sess.referrer_info.qs[query_term]){ sess.search.engine = 'Unknown'; sess.search.query = res; return true; } - }); + }); } - sess.referrer = doc.referrer; - sess.url = win.location.href; - sess.path = win.location.pathname; - sess.start = (new Date()).getTime(); - sess.last_visit = sess.start; if (cookie_name){ utils.set_cookie(cookie_name, JSON.stringify(sess), expires); } } else { sess = JSON.parse(sess); @@ -279,7 +288,7 @@ } else { if (opts.gapi_location){ return modules.gapi()(cb); - } else { cb({err: true, source: 'ipinfodb'}); } + } else { cb({err: true, source: 'ipinfodb', err_msg: data['statusMessage']}); } } } utils.embed_script('http://api.ipinfodb.com/v3/ip-city/?key='+ api_key +'&format=json&callback=ipinfocb'); @@ -304,7 +313,7 @@ } else if (opts.gapi_location){ session_loader.modules['location'] = modules.gapi_location(); } - // Setup session Object + // Setup session object var asyncs = 0, check_async = function(){; if (asyncs == 0){ win.session_loaded && win.session_loaded(win.session); } }; diff --git a/session.min.js b/session.min.js index 5713c43..840b7e0 100644 --- a/session.min.js +++ b/session.min.js @@ -1,8 +1,8 @@ /** - * session.js 0.0.2 + * session.js 0.2 * (c) 2012 Iain, CodeJoust * session is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c={use_html5_location:!1,ipinfodb_key:null,gapi_location:!0,session_days:32,location_cookie_name:"location",session_cookie_name:"first_session",location_cookie_hours:2};if("session_opts"in a)for(opt in a.session_opts)c[opt]=a.session_opts[opt];var d={detect_browser:function(){return{browser:this.searchString(this.dataBrowser),version:this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion),OS:this.searchString(this.dataOS)}},searchString:function(a){for(var b=0;b0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Sat, 7 Jan 2012 11:39:24 -0500 Subject: [PATCH 09/29] updating demo --- session.js | 5 +++-- session.min.js | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/session.js b/session.js index 3ef90ba..290cf0c 100644 --- a/session.js +++ b/session.js @@ -223,9 +223,10 @@ {nm: "Baidu", host:"baidu.com", query:"wd"}, ]; utils.find(engines, function(engine){ - if (sess.referrer_info.host.indexOf(engine.host) != -1 && sess.referrer_info.qs[engine.query]){ + if (sess.referrer_info.host.indexOf(engine.host) != -1){ sess.search.engine = engine.nm; - sess.search.query = engine.query; + sess.search.query = sess.referrer_info.qs[engine.query]; + sess.search.terms = sess.search.query.split(' '); return true; } }); diff --git a/session.min.js b/session.min.js index 840b7e0..5224adc 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,session_days:32,location_cookie_name:"location",session_cookie_name:"first_session",location_cookie_hours:2};if("session_opts"in a)for(opt in a.session_opts)c[opt]=a.session_opts[opt];var d={detect_browser:function(){return{browser:this.searchString(this.dataBrowser),version:this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion),OS:this.searchString(this.dataOS)}},searchString:function(a){for(var b=0;b0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Sat, 7 Jan 2012 12:01:28 -0500 Subject: [PATCH 10/29] Version bump --- session.js | 4 ++-- session.min.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/session.js b/session.js index 290cf0c..1e6fa80 100644 --- a/session.js +++ b/session.js @@ -1,5 +1,5 @@ /** - * session.js 0.2 + * session.js 0.3 * (c) 2012 Iain, CodeJoust * session is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. @@ -319,7 +319,7 @@ if (asyncs == 0){ win.session_loaded && win.session_loaded(win.session); } }; win.modules = session_loader.modules; - win.session = {api_version: 0.2} + win.session = {api_version: 0.3} for (module_name in session_loader.modules){ (function(module_name){ var module_runner = session_loader.modules[module_name]; diff --git a/session.min.js b/session.min.js index 5224adc..6318c79 100644 --- a/session.min.js +++ b/session.min.js @@ -1,8 +1,8 @@ /** - * session.js 0.2 + * session.js 0.3 * (c) 2012 Iain, CodeJoust * session is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,session_days:32,location_cookie_name:"location",session_cookie_name:"first_session",location_cookie_hours:2};if("session_opts"in a)for(opt in a.session_opts)c[opt]=a.session_opts[opt];var d={detect_browser:function(){return{browser:this.searchString(this.dataBrowser),version:this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion),OS:this.searchString(this.dataOS)}},searchString:function(a){for(var b=0;b0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d Date: Sat, 7 Jan 2012 22:08:30 -0500 Subject: [PATCH 11/29] updating demo --- demo.html | 153 +++++++++++ ipinfodb_demo.html | 25 +- session.js | 649 ++++++++++++++++++++++++--------------------- session.min.js | 6 +- 4 files changed, 521 insertions(+), 312 deletions(-) create mode 100644 demo.html diff --git a/demo.html b/demo.html new file mode 100644 index 0000000..d7f1118 --- /dev/null +++ b/demo.html @@ -0,0 +1,153 @@ + + + Demo for Session.js + + + + +

Session.js Demo Page

+

Demo output:

+
+    loading...
+  
+ +

Session.JS on GitHub by Iain

+ + + + diff --git a/ipinfodb_demo.html b/ipinfodb_demo.html index c5cb30a..1e05175 100644 --- a/ipinfodb_demo.html +++ b/ipinfodb_demo.html @@ -140,18 +140,21 @@

Using ipinfodb for location lookup

} } }());

Session.JS on GitHub by Iain

+ diff --git a/session.js b/session.js index 1e6fa80..5229b2b 100644 --- a/session.js +++ b/session.js @@ -1,349 +1,402 @@ /** - * session.js 0.3 + * session.js 0.4.1 * (c) 2012 Iain, CodeJoust - * session is freely distributable under the MIT license. + * session.js is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js */ (function(win, doc){ - var opts = { + // Changing the API Version invalidates olde cookies with previous api version tags. + var API_VERSION = 0.4; + + // Settings: defaults + var options = { + // Use the HTML5 Geolocation API + // this ONLY returns lat & long, no city/address use_html5_location: false, - // use html5 location -- this _ONLY_ return lat/long, not an city/address + // Attempts to use IPInfoDB if provided a valid key + // Get a key at http://ipinfodb.com/register.php ipinfodb_key: false, - // attempts to use ipinfodb if provided an API key -- get a key at http://ipinfodb.com/register.php + // Leaving true allows for fallback for both + // the HTML5 location and the IPInfoDB gapi_location: true, - // leaving true allows for fallback for both the html5 location and the ipinfodb - session_days: 32, - // how many days session information is kept in a cookie - location_cookie_name: 'location', - // the name of the location cookie - // -- warning: different providers use the same cookie - // -- if switching providers, remember to use another cookie or provide checks for old cookies - session_cookie_name: 'first_session', - // session cookie name - location_cookie_hours: 2 - // lifetime of the location cookie - } - if ('session_opts' in win){ - for (opt in win.session_opts){ - opts[opt] = win.session_opts[opt]; + // Name of the location cookie + // - WARNING: different providers use the same cookie + // - if switching providers, remember to use another cookie or provide checks for old cookies + location_cookie: "location", + // Location cookie expiration in hours + location_cookie_timeout: 2, + // Session expiration in days + session_timeout: 32, + // Session cookie name + session_cookie: "first_session" + }; + + // Session object + var SessionRunner = function(){ + // Merge options + if(win.session && win.session.options) { + for (option in win.session.options){ + options[option] = win.session.options[option]; } } - } - var BrowserDetect = { // from quirksmode.org/js/detect.html - detect_browser: function(){ - return {browser: this.searchString(this.dataBrowser), - version: this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion), - OS: this.searchString(this.dataOS)}; - }, - searchString: function (data) { - for (var i=0;i 1){ + for (i = 0; i < fallbacks.length; i++){ + var terms = session.referrer_info.query[fallbacks[i]]; + if (terms){ + session.search.engine = "Unknown"; + session.search.query = terms; session.search.terms = terms.split(" "); + break; } - }); + } } - if (cookie_name){ utils.set_cookie(cookie_name, JSON.stringify(sess), expires); } } else { - sess = JSON.parse(sess); - sess.last_visit = (new Date()).getTime(); - sess.visits += 1; - utils.set_cookie(cookie_name, JSON.stringify(sess), expires) + session.last_visit = new Date().getTime(); + session.visits++; } - return sess; + util.set_cookie(cookie, util.package_obj(session), expires); + return session; }, - html5_location: function(){ - return function(cb){ - navigator.geolocation.getCurrentPosition(function(position){ - position['source'] = 'html5'; - return position - }, function(err_msg){ - if (opts.gapi_location){ modules.gapi_location()(cb); } - else { cb({err: true, source: 'html5'}); } + html5_location: function() { + return function(callback){ + navigator.geolocation.getCurrentPosition(function(pos){ + pos.source = 'html5'; + callback(pos); + }, function(err) { + if (options.gapi_location){ + modules.gapi_location()(callback); + } else { + callback({error: true, source: 'html5'}); } }); - - } + }; }, - gapi_location: function(){ - return function(cb){ - var loc = null; - if (!utils.get_cookie(opts.location_cookie_name)){ - win.gloader_loaded = function(){ - if ('google' in window) { + gapi_location: function() { + return function(callback){ + var location = util.get_obj(options.location_cookie); + if (!location || location.source !== 'google'){ + win.gloaderReady = function() { + if ("google" in win){ if (win.google.loader.ClientLocation){ - win.google.loader.ClientLocation.source = 'google'; - cb(win.google.loader.ClientLocation); + win.google.loader.ClientLocation.source = "google"; + callback(win.google.loader.ClientLocation); } else { - cb({err: true, source: 'google'}) + callback({error: true, source: "google"}); } - utils.set_cookie(opts.location_cookie_name,utils.stringify_json(win.google.loader.ClientLocation), 1000 * 60 * 60 * opts.location_cookie_hours);} } - utils.embed_script('https://www.google.com/jsapi?callback=gloader_loaded'); - } else { cb(utils.parse_json(utils.get_cookie(opts.location_cookie_name))); } - } + util.set_cookie( + options.location_cookie, + util.package_obj(win.google.loader.ClientLocation), + options.location_cookie_timeout * 60 * 60 * 1000); + }} + util.embed_script("https://www.google.com/jsapi?callback=gloaderReady"); + } else { + callback(location); + }} }, - ipinfodb_location: function(api_key){ - return function(cb){ - var loc_cookie = utils.get_cookie(opts.location_cookie_name); - if (loc_cookie){ return cb(JSON.parse(loc_cookie)); } + ipinfodb_location: function(apiKey){ + return function (callback){ + var location_cookie = util.get_obj(options.location_cookie); + if (location_cookie && location_cookie.source === 'ipinfodb'){ callback(location_cookie); } win.ipinfocb = function(data){ - if (data['statusCode'] == 'OK'){ - data['source'] = 'ipinfodb'; - utils.set_cookie(opts.location_cookie_name, JSON.stringify(data), 1000 * 60 * 60 * opts.location_cookie_hours); - cb(data); + if (data.statusCode === "OK"){ + data.source = "ipinfodb"; + util.set_cookie( + options.location_cookie, + util.package_obj(data), + options.location_cookie * 60 * 60 * 1000); + callback(data); } else { - if (opts.gapi_location){ - return modules.gapi()(cb); - } else { cb({err: true, source: 'ipinfodb', err_msg: data['statusMessage']}); } - } + if (options.gapi_location){ return modules.gapi_location()(callback); } + else { callback({error: true, source: "ipinfodb", message: data.statusMessage}); } + }} + util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + apiKey + "&format=json&callback=ipinfocb"); + }} + }; + + // Utilities + var util = win.util = { + parse_url: function(url_str){ + var a = doc.createElement("a"), query = {}; + a.href = url_str; query_str = a.search.substr(1); + // Disassemble query string + if (query_str != ''){ + var pairs = query_str.split("&"), i = 0, + length = pairs.length, parts; + for (; i < length; i++){ + parts = pairs[i].split("="); + if (parts.length === 2){ + query[parts[0]] = decodeURI(parts[1]); } } - utils.embed_script('http://api.ipinfodb.com/v3/ip-city/?key='+ api_key +'&format=json&callback=ipinfocb'); } - } - } - var session_loader = { - modules: { - locale: modules.locale(), - cur_session: modules.session(), - orig_session: modules.session(opts.session_cookie_name, 1000 * 60 * 60 * 24 * opts.session_days), - browser: modules.browser(), - plugins: modules.plugins(), - device: modules.device() + return { + host: a.host, + path: a.pathname, + protocol: a.protocol, + port: a.port === '' ? 80 : a.port, + search: a.search, + query: query } }, - init: function(){ - // location switch - if (opts.use_html5_location){ - session_loader.modules['location'] = modules.html5_location(); - } else if (opts.ipinfodb_key){ - session_loader.modules['location'] = modules.ipinfodb_location(opts.ipinfodb_key); - } else if (opts.gapi_location){ - session_loader.modules['location'] = modules.gapi_location(); - } - // Setup session object - var asyncs = 0, check_async = function(){; - if (asyncs == 0){ win.session_loaded && win.session_loaded(win.session); } - }; - win.modules = session_loader.modules; - win.session = {api_version: 0.3} - for (module_name in session_loader.modules){ - (function(module_name){ - var module_runner = session_loader.modules[module_name]; - if (typeof(module_runner) === 'function'){ - try { - var ret = module_runner; - if (typeof(ret) === 'function'){ - asyncs++; - ret(function(data){ - win.session[module_name] = data; - asyncs--; - check_async(); - }); - } else { - win.session[module_name] = ret; - } - } catch (e) { if (typeof(console) !== 'undefined'){ console.log(e); } } - } else { - win.session[module_name] = module_runner; - } - })(module_name); + set_cookie: function(name, value, expires, path){ + if (!doc.cookie || !name || !value){ return null; } + // set path + path = path ? "; path=" + path : "; path=/"; + // calculate expiration date + if (expires) { + var date = new Date(); + date.setTime(date.getTime() + expires); + expires = "; expires=" + date.toGMTString(); + } else { expires = ""; } + // set cookie + return (doc.cookie = (name + "=" + value + expires + path)); + }, + get_cookie: function(cookie_name){ // from quirksmode.org + var nameEQ = cookie_name + "="; + var ca = doc.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; + }, + embed_script: function(url){ + var element = doc.createElement("script"); + element.type = "text/javascript"; + element.src = url; + doc.getElementsByTagName("body")[0].appendChild(element); + }, + package_obj: function (obj){ + obj.version = API_VERSION; + var ret = JSON.stringify(obj); + delete obj.version; return ret; + }, + get_obj: function(cookie_name){ + var obj = JSON.parse(util.get_cookie(cookie_name)); + if (obj && obj.version == API_VERSION){ + delete obj.version; return obj; } - check_async(); } }; - session_loader.init(); -})(window, document); + + // JSON + var JSON = { + parse: (win.JSON && win.JSON.parse) || function(data) { + try { + if (typeof data !== "string" || !data){ return null; } + return (new Function("return " + data))(); + } catch (e){ return null; } + }, + stringify: (win.JSON && win.JSON.stringify) || function(object) { + var type = typeof object; + if (type !== "object" || object === null) { + if (type === "string"){ return '"' + object + '"'; } + } else { + var k, v, json = [], + isArray = (object && object.constructor === Array); + for (k in object ) { + v = object[k]; type = typeof v; + if (type === "string") + v = '"' + v + '"'; + else if (type === "object" && v !== null) + v = this.stringify(v); + json.push((isArray ? "" : '"' + k + '":') + v); + } + return (isArray ? "[" : "{") + json.join(",") + (isArray ? "]" : "}"); + } } }; + + // Initialize SessionRunner + SessionRunner(); + +})(window, document); \ No newline at end of file diff --git a/session.min.js b/session.min.js index 6318c79..9eb68d8 100644 --- a/session.min.js +++ b/session.min.js @@ -1,8 +1,8 @@ /** - * session.js 0.3 + * session.js 0.4.1 * (c) 2012 Iain, CodeJoust - * session is freely distributable under the MIT license. + * session.js is freely distributable under the MIT license. * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,session_days:32,location_cookie_name:"location",session_cookie_name:"first_session",location_cookie_hours:2};if("session_opts"in a)for(opt in a.session_opts)c[opt]=a.session_opts[opt];var d={detect_browser:function(){return{browser:this.searchString(this.dataBrowser),version:this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion),OS:this.searchString(this.dataOS)}},searchString:function(a){for(var b=0;b0){c_start=document.cookie.indexOf(a+"=");if(c_start!=-1){c_start=c_start+a.length+1,c_end=document.cookie.indexOf(";",c_start),c_end==-1&&(c_end=document.cookie.length);return unescape(document.cookie.substring(c_start,c_end))}}return null},each:function(a,b,c){if(a!=null)if(a.length===+a.length){for(var d=0,e=a.length;d1)for(k=0;k Date: Sat, 7 Jan 2012 23:24:05 -0500 Subject: [PATCH 12/29] Updating script --- session.js | 12 ++++++------ session.min.js | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/session.js b/session.js index 5229b2b..70df11d 100644 --- a/session.js +++ b/session.js @@ -78,17 +78,17 @@ for (var name in this.modules){ module = self.modules[name]; if(typeof module === "function"){ - //try { + try { asynchs++; module(function(data){ self.modules[name] = data; asynchs--; check_asynch(); }); - /*} catch(err){ + } catch(err){ if (win.console && typeof(console.log) === "function"){ console.log(err); } - }*/ + } } else { self.modules[name] = module; } @@ -340,7 +340,7 @@ expires = "; expires=" + date.toGMTString(); } else { expires = ""; } // set cookie - return (doc.cookie = (name + "=" + value + expires + path)); + return (doc.cookie = (name + "=" + encodeURIComponent(value) + expires + path)); }, get_cookie: function(cookie_name){ // from quirksmode.org var nameEQ = cookie_name + "="; @@ -348,7 +348,7 @@ 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); } + if (c.indexOf(nameEQ) == 0){ return decodeURIComponent(c.substring(nameEQ.length, c.length)); } } return null; }, embed_script: function(url){ @@ -399,4 +399,4 @@ // Initialize SessionRunner SessionRunner(); -})(window, document); \ No newline at end of file +})(window, document); diff --git a/session.min.js b/session.min.js index 9eb68d8..e22baa4 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c=.4,d={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:2,session_timeout:32,session_cookie:"first_session"},e=function(){if(a.session&&a.session.options)for(option in a.session.options)d[option]=a.session.options[option];this.modules={api_version:c,locale:g.locale(),current_session:g.session(),original_session:g.session(d.session_cookie,d.session_timeout*24*60*60*1e3),browser:g.browser(),plugins:g.plugins(),device:g.device()},d.use_html5_location?this.modules.location=g.html5_location():d.ipinfodb_key?this.modules.location=g.ipinfodb_location(d.ipinfodb_key):d.gapi_location&&(this.modules.location=g.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var e=0,f,h,i=this,j=function(){e===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules)f=i.modules[k],typeof f=="function"?(e++,f(function(a){i.modules[k]=a,e--,j()})):i.modules[k]=f;j()},f={detect:function(){return{browser:this.search(this.data.browser),version:this.search(navigator.userAgent)||this.search(navigator.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Sat, 7 Jan 2012 23:31:04 -0500 Subject: [PATCH 13/29] Name mixup --- demo.html | 153 ----------------------------------------------------- index.html | 27 +++++----- 2 files changed, 15 insertions(+), 165 deletions(-) delete mode 100644 demo.html diff --git a/demo.html b/demo.html deleted file mode 100644 index d7f1118..0000000 --- a/demo.html +++ /dev/null @@ -1,153 +0,0 @@ - - - Demo for Session.js - - - - -

Session.js Demo Page

-

Demo output:

-
-    loading...
-  
- -

Session.JS on GitHub by Iain

- - - - diff --git a/index.html b/index.html index 8974229..d7f1118 100644 --- a/index.html +++ b/index.html @@ -42,9 +42,7 @@

Session.js Demo Page

} } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions + gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { @@ -120,30 +118,35 @@

Session.js Demo Page

} } // If the JSON object does not yet have a stringify met©hod, give it one. if (typeof JSONf.stringify !== 'function') { - JSONf.stringify = function (value, replacer, space) { + JSONf.stringify = function(value, replacer, space){ // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; - if (typeof space === 'number') { + if (typeof(space) === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { + if (replacer && typeof(replacer) !== 'function' && + (typeof(replacer) !== 'object' || + typeof(replacer.length) !== 'number')) { throw new Error('JSON.stringify'); } return str('', {'': value}); } } }());

Session.JS on GitHub by Iain

From fbacd56f718940272b42242e7f967ad9604e8c05 Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Sun, 8 Jan 2012 08:30:31 -0500 Subject: [PATCH 14/29] updating js demo --- session.js | 13 ++++++++----- session.min.js | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/session.js b/session.js index 70df11d..ce586dc 100644 --- a/session.js +++ b/session.js @@ -41,6 +41,8 @@ options[option] = win.session.options[option]; } } // Modules to run + // If the module has arguments, + // it _needs_ to return a callback function. this.modules = { api_version: API_VERSION, locale: modules.locale(), @@ -163,10 +165,11 @@ navigator.systemLanguage || navigator.userLanguage ).split("-"); - return { - country: lang[1].toLowerCase(), - lang: lang[0].toLowerCase() - }; + if (lang.length == 2){ + return { country: lang[1].toLowerCase(), lang: lang[0].toLowerCase() }; + } else if (lang) { + return {lang: lang[0].toLowerCase(), country: null }; + } else { return{lang: null, country: null }; } }, device: function() { var device = { @@ -307,7 +310,7 @@ }; // Utilities - var util = win.util = { + var util = { parse_url: function(url_str){ var a = doc.createElement("a"), query = {}; a.href = url_str; query_str = a.search.substr(1); diff --git a/session.min.js b/session.min.js index e22baa4..1ffe69b 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c=.4,d={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:2,session_timeout:32,session_cookie:"first_session"},e=function(){if(a.session&&a.session.options)for(option in a.session.options)d[option]=a.session.options[option];this.modules={api_version:c,locale:g.locale(),current_session:g.session(),original_session:g.session(d.session_cookie,d.session_timeout*24*60*60*1e3),browser:g.browser(),plugins:g.plugins(),device:g.device()},d.use_html5_location?this.modules.location=g.html5_location():d.ipinfodb_key?this.modules.location=g.ipinfodb_location(d.ipinfodb_key):d.gapi_location&&(this.modules.location=g.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var e=0,f,h,i=this,j=function(){e===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{e++,f(function(a){i.modules[k]=a,e--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},f={detect:function(){return{browser:this.search(this.data.browser),version:this.search(navigator.userAgent)||this.search(navigator.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Sun, 8 Jan 2012 09:21:06 -0500 Subject: [PATCH 15/29] updating demo --- session.js | 46 +++++++++++++++++++++------------------------- session.min.js | 2 +- 2 files changed, 22 insertions(+), 26 deletions(-) diff --git a/session.js b/session.js index ce586dc..5914ca9 100644 --- a/session.js +++ b/session.js @@ -332,27 +332,24 @@ search: a.search, query: query } }, - set_cookie: function(name, value, expires, path){ - if (!doc.cookie || !name || !value){ return null; } - // set path - path = path ? "; path=" + path : "; path=/"; - // calculate expiration date - if (expires) { - var date = new Date(); - date.setTime(date.getTime() + expires); - expires = "; expires=" + date.toGMTString(); - } else { expires = ""; } - // set cookie - return (doc.cookie = (name + "=" + encodeURIComponent(value) + expires + path)); + set_cookie: function(cname, value, expires, options){ // from jquery.cookie.j + if (!doc.cookie || !cname || !value){ return null; } + if (!options){ var options = {}; } + if (value === null || value === undefined){ expires = -1; } + if (typeof expires === 'number') { + var days = expires, t = expires = new Date(); + t.setDate(t.getDate() + days); } + return (document.cookie = [ + encodeURIComponent(cname), '=', + options.raw ? value : encodeURIComponent(String(value)), + options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE + options.path ? '; path=' + options.path : '', + options.domain ? '; domain=' + options.domain : '', + options.secure ? '; secure' : '' + ].join('')); }, - get_cookie: function(cookie_name){ // from quirksmode.org - var nameEQ = cookie_name + "="; - var ca = doc.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 decodeURIComponent(c.substring(nameEQ.length, c.length)); } - } return null; + get_cookie: function(cookie_name, result){ // from jquery.cookie.js + return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookie_name) + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null; }, embed_script: function(url){ var element = doc.createElement("script"); @@ -366,7 +363,8 @@ delete obj.version; return ret; }, get_obj: function(cookie_name){ - var obj = JSON.parse(util.get_cookie(cookie_name)); + var obj; + try { obj = JSON.parse(util.get_cookie(cookie_name)); } catch(e){}; if (obj && obj.version == API_VERSION){ delete obj.version; return obj; } @@ -375,13 +373,11 @@ // JSON var JSON = { - parse: (win.JSON && win.JSON.parse) || function(data) { - try { + parse: (win.JSON && win.JSON.parse) || function(data){ if (typeof data !== "string" || !data){ return null; } return (new Function("return " + data))(); - } catch (e){ return null; } }, - stringify: (win.JSON && win.JSON.stringify) || function(object) { + stringify: (win.JSON && win.JSON.stringify) || function(object){ var type = typeof object; if (type !== "object" || object === null) { if (type === "string"){ return '"' + object + '"'; } diff --git a/session.min.js b/session.min.js index 1ffe69b..888e0cd 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c=.4,d={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:2,session_timeout:32,session_cookie:"first_session"},e=function(){if(a.session&&a.session.options)for(option in a.session.options)d[option]=a.session.options[option];this.modules={api_version:c,locale:g.locale(),current_session:g.session(),original_session:g.session(d.session_cookie,d.session_timeout*24*60*60*1e3),browser:g.browser(),plugins:g.plugins(),device:g.device()},d.use_html5_location?this.modules.location=g.html5_location():d.ipinfodb_key?this.modules.location=g.ipinfodb_location(d.ipinfodb_key):d.gapi_location&&(this.modules.location=g.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var e=0,f,h,i=this,j=function(){e===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{e++,f(function(a){i.modules[k]=a,e--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},f={detect:function(){return{browser:this.search(this.data.browser),version:this.search(navigator.userAgent)||this.search(navigator.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Sun, 8 Jan 2012 12:54:15 -0500 Subject: [PATCH 16/29] updating demo --- session.js | 30 ++++++++++++++---------------- session.min.js | 2 +- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/session.js b/session.js index 5914ca9..233a123 100644 --- a/session.js +++ b/session.js @@ -21,15 +21,15 @@ // Leaving true allows for fallback for both // the HTML5 location and the IPInfoDB gapi_location: true, - // Name of the location cookie + // Name of the location cookie (set blank to disable cookie) // - WARNING: different providers use the same cookie // - if switching providers, remember to use another cookie or provide checks for old cookies location_cookie: "location", // Location cookie expiration in hours - location_cookie_timeout: 2, + location_cookie_timeout: 5, // Session expiration in days session_timeout: 32, - // Session cookie name + // Session cookie name (set blank to disable cookie) session_cookie: "first_session" }; @@ -254,7 +254,7 @@ util.set_cookie(cookie, util.package_obj(session), expires); return session; }, - html5_location: function() { + html5_location: function(){ return function(callback){ navigator.geolocation.getCurrentPosition(function(pos){ pos.source = 'html5'; @@ -267,11 +267,11 @@ }); }; }, - gapi_location: function() { + gapi_location: function(){ return function(callback){ var location = util.get_obj(options.location_cookie); if (!location || location.source !== 'google'){ - win.gloaderReady = function() { + win.gloader_ready = function() { if ("google" in win){ if (win.google.loader.ClientLocation){ win.google.loader.ClientLocation.source = "google"; @@ -284,12 +284,12 @@ util.package_obj(win.google.loader.ClientLocation), options.location_cookie_timeout * 60 * 60 * 1000); }} - util.embed_script("https://www.google.com/jsapi?callback=gloaderReady"); + util.embed_script("https://www.google.com/jsapi?callback=gloader_ready"); } else { callback(location); }} }, - ipinfodb_location: function(apiKey){ + ipinfodb_location: function(api_key){ return function (callback){ var location_cookie = util.get_obj(options.location_cookie); if (location_cookie && location_cookie.source === 'ipinfodb'){ callback(location_cookie); } @@ -305,7 +305,7 @@ if (options.gapi_location){ return modules.gapi_location()(callback); } else { callback({error: true, source: "ipinfodb", message: data.statusMessage}); } }} - util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + apiKey + "&format=json&callback=ipinfocb"); + util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + api_key + "&format=json&callback=ipinfocb"); }} }; @@ -332,20 +332,18 @@ search: a.search, query: query } }, - set_cookie: function(cname, value, expires, options){ // from jquery.cookie.j + set_cookie: function(cname, value, expires, options){ // from jquery.cookie.js if (!doc.cookie || !cname || !value){ return null; } if (!options){ var options = {}; } if (value === null || value === undefined){ expires = -1; } - if (typeof expires === 'number') { - var days = expires, t = expires = new Date(); - t.setDate(t.getDate() + days); } + if (expires){ options.expires = (new Date().getTime()) + expires; } return (document.cookie = [ encodeURIComponent(cname), '=', - options.raw ? value : encodeURIComponent(String(value)), - options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE + encodeURIComponent(String(value)), + options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', - options.secure ? '; secure' : '' + (win.location && win.location.protocol === 'https:') ? '; secure' : '' ].join('')); }, get_cookie: function(cookie_name, result){ // from jquery.cookie.js diff --git a/session.min.js b/session.min.js index 888e0cd..06b1f04 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b){var c=.4,d={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:2,session_timeout:32,session_cookie:"first_session"},e=function(){if(a.session&&a.session.options)for(option in a.session.options)d[option]=a.session.options[option];this.modules={api_version:c,locale:g.locale(),current_session:g.session(),original_session:g.session(d.session_cookie,d.session_timeout*24*60*60*1e3),browser:g.browser(),plugins:g.plugins(),device:g.device()},d.use_html5_location?this.modules.location=g.html5_location():d.ipinfodb_key?this.modules.location=g.ipinfodb_location(d.ipinfodb_key):d.gapi_location&&(this.modules.location=g.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var e=0,f,h,i=this,j=function(){e===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{e++,f(function(a){i.modules[k]=a,e--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},f={detect:function(){return{browser:this.search(this.data.browser),version:this.search(navigator.userAgent)||this.search(navigator.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Sun, 8 Jan 2012 19:23:38 -0500 Subject: [PATCH 17/29] Demos use edge js file --- index.html | 2 +- ipinfodb_demo.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index d7f1118..8de26e7 100644 --- a/index.html +++ b/index.html @@ -148,6 +148,6 @@

Session.js Demo Page

} }; - + diff --git a/ipinfodb_demo.html b/ipinfodb_demo.html index 1e05175..e8f62ca 100644 --- a/ipinfodb_demo.html +++ b/ipinfodb_demo.html @@ -157,6 +157,6 @@

Using ipinfodb for location lookup

} }; - + From 077711ada209a1c24de15a3d0e84faa8d7a98167 Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Mon, 9 Jan 2012 09:43:47 -0500 Subject: [PATCH 18/29] Moving js to gh-pages --- index.html | 2 +- ipinfodb_demo.html | 2 +- session-0.4.js | 414 +++++++++++++++++++++++++++++++++++++++++++++ session-0.4.min.js | 8 + session.js | 77 +++++---- session.min.js | 2 +- 6 files changed, 471 insertions(+), 34 deletions(-) create mode 100644 session-0.4.js create mode 100644 session-0.4.min.js diff --git a/index.html b/index.html index 8de26e7..d7f1118 100644 --- a/index.html +++ b/index.html @@ -148,6 +148,6 @@

Session.js Demo Page

} }; - + diff --git a/ipinfodb_demo.html b/ipinfodb_demo.html index e8f62ca..1e05175 100644 --- a/ipinfodb_demo.html +++ b/ipinfodb_demo.html @@ -157,6 +157,6 @@

Using ipinfodb for location lookup

} }; - + diff --git a/session-0.4.js b/session-0.4.js new file mode 100644 index 0000000..d397b70 --- /dev/null +++ b/session-0.4.js @@ -0,0 +1,414 @@ +/** + * session.js 0.4.1 + * (c) 2012 Iain, CodeJoust + * session.js is freely distributable under the MIT license. + * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. + * This version uses google's jsapi library for location services. + * For details, see: https://github.com/codejoust/session.js + */ +(function(win, doc, nav){ + // Changing the API Version invalidates olde cookies with previous api version tags. + var API_VERSION = 0.4; + + // Settings: defaults + var options = { + // Use the HTML5 Geolocation API + // this ONLY returns lat & long, no city/address + use_html5_location: false, + // Attempts to use IPInfoDB if provided a valid key + // Get a key at http://ipinfodb.com/register.php + ipinfodb_key: false, + // Leaving true allows for fallback for both + // the HTML5 location and the IPInfoDB + gapi_location: true, + // Name of the location cookie (set blank to disable cookie) + // - WARNING: different providers use the same cookie + // - if switching providers, remember to use another cookie or provide checks for old cookies + location_cookie: "location", + // Location cookie expiration in hours + location_cookie_timeout: 5, + // Session expiration in days + session_timeout: 32, + // Session cookie name (set blank to disable cookie) + session_cookie: "first_session" + }; + + // Session object + var SessionRunner = function(){ + // Merge options + if(win.session && win.session.options) { + for (option in win.session.options){ + options[option] = win.session.options[option]; } + } + // Modules to run + // If the module has arguments, + // it _needs_ to return a callback function. + this.modules = { + api_version: API_VERSION, + locale: modules.locale(), + current_session: modules.session(), + original_session: modules.session( + options.session_cookie, + options.session_timeout * 24 * 60 * 60 * 1000), + browser: modules.browser(), + plugins: modules.plugins(), + time: modules.time(), // uses callback + device: modules.device() + }; + // Location switch + if (options.use_html5_location){ + this.modules.location = modules.html5_location(); + } else if (options.ipinfodb_key){ + this.modules.location = modules.ipinfodb_location(options.ipinfodb_key); + } else if (options.gapi_location){ + this.modules.location = modules.gapi_location(); + } + // Cache win.session.start + if (win.session && win.session.start){ + var start = win.session.start; + } + // Set up checking, if all modules are ready + var asynchs = 0, module, result, self = this, + check_asynch = function(){ + if (asynchs === 0){ + // Map over results + win.session = self.modules; + // Run start calback + if (start){ start(self.modules); } + } + }; + // Run asynchronous methods + for (var name in this.modules){ + module = self.modules[name]; + if(typeof module === "function"){ + try { + asynchs++; + module(function(data){ + self.modules[name] = data; + asynchs--; + check_asynch(); + }); + } catch(err){ + if (win.console && typeof(console.log) === "function"){ + console.log(err); } + } + } else { + self.modules[name] = module; + } + } + check_asynch(); + }; + + + // Browser (and OS) detection + var browser = { + detect: function(){ + return { + browser: this.search(this.data.browser), + version: this.search(nav.userAgent) || this.search(nav.appVersion), + os: this.search(this.data.os) + } }, + search: function(data) { + if (typeof data === "object"){ + // search for string match + for(var i = 0; i < data.length; i++) { + var dataString = data[i].string, + dataProp = data[i].prop; + this.version_string = data[i].versionSearch || data[i].identity; + if (dataString){ + if (dataString.indexOf(data[i].subString) != -1){ + return data[i].identity; + } + } else if (dataProp){ + return data[i].identity; + } + } + } else { + // search for version number + var index = data.indexOf(this.version_string); + if (index == -1) return; + return parseFloat(data.substr(index + this.version_string.length + 1)); + } + }, + data: { + browser: [ + { string: nav.userAgent, subString: "Chrome", identity: "Chrome" }, + { string: nav.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, + { string: nav.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, + { prop: win.opera, identity: "Opera", versionSearch: "Version" }, + { string: nav.vendor, subString: "iCab",identity: "iCab" }, + { string: nav.vendor, subString: "KDE", identity: "Konqueror" }, + { string: nav.userAgent, subString: "Firefox", identity: "Firefox" }, + { string: nav.vendor, subString: "Camino", identity: "Camino" }, + { string: nav.userAgent, subString: "Netscape", identity: "Netscape" }, + { string: nav.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, + { string: nav.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, + { string: nav.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } + ], + os: [ + { string: nav.platform, subString: "Win", identity: "Windows" }, + { string: nav.platform, subString: "Mac", identity: "Mac" }, + { string: nav.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, + { string: nav.userAgent, subString: "iPad", identitiy: "iPad" }, + { string: nav.platform, subString: "Linux", identity: "Linux" }, + { string: nav.userAgent, subString: "Android", identity: "Android" } + ]} + }; + + var modules = { + browser: function(){ + return browser.detect(); + }, + time: function(){ + // wrapping in a callback to catch failures... + try { + var d = new Date('Sat, 07 Jan 2012 04:10:00 +0000'); + d = d.toString(); + d = d.match(/\(([^]+)\)/)[1]; + // split date and grab timezone estimation. + // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ + var d1 = new Date(), d2 = new Date(); + d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); + return({timezone: d, tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); + // Gives a browser estimation, not guaranteed to be correct. + } catch (e){ return {err: true, msg: e}; } + }, + locale: function() { + var lang = ( + nav.language || + nav.browserLanguage || + nav.systemLanguage || + nav.userLanguage + ).split("-"); + if (lang.length == 2){ + return { country: lang[1].toLowerCase(), lang: lang[0].toLowerCase() }; + } else if (lang) { + return {lang: lang[0].toLowerCase(), country: null }; + } else { return{lang: null, country: null }; } + }, + device: function() { + var device = { + screen: { + width: screen.width, + height: screen.height + } + }; + var html = doc.documentElement, + body = doc.getElementsByTagName("body")[0]; + device.viewport = { + width: win.innerWidth || html.clientWidth || body.clientWidth, + height: win.innerHeight || html.clientHeight || body.clientHeight + }; + device.is_tablet = !!nav.userAgent.match(/(iPad|SCH-I800|xoom|kindle)/i); + device.is_phone = !device.isTablet && !!nav.userAgent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i); + device.is_mobile = (device.is_tablet || device.is_phone); + return device; + }, + plugins: function(){ + var check_plugin = function(name){ + if (nav.plugins){ + var plugin, i = 0, length = nav.plugins.length; + for (; i < length; i++ ){ + plugin = nav.plugins[i]; + if (plugin && plugin.name && plugin.name.toLowerCase().indexOf(name) !== -1){ + return true; + } } + return false; + } return false; + } + return { + flash: check_plugin("flash"), + silverlight: check_plugin("silverlight"), + java: check_plugin("java"), + quicktime: check_plugin("quicktime") + }; + }, + session: function (cookie, expires){ + var session = util.get_obj(cookie); + if (session == null){ + session = { + visits: 1, + start: new Date().getTime(), last_visit: new Date().getTime(), + url: win.location.href, path: win.location.pathname, + referrer: doc.referrer, referrer_info: util.parse_url(doc.referrer), + search: { engine: null, query: null } + }; + var search_engines = [ + { name: "Google", host: "google", query: "q" }, + { name: "Bing", host: "bing.com", query: "q" }, + { name: "Yahoo", host: "search.yahoo", query: "p" }, + { name: "AOL", host: "search.aol", query: "q" }, + { name: "Ask", host: "ask.com", query: "q" }, + { name: "Baidu", host: "baidu.com", query: "wd" } + ], length = search_engines.length, + engine, match, i = 0, + fallbacks = 'q query term p wd query text'.split(' '); + for (i = 0; i < length; i++){ + engine = search_engines[i]; + if (session.referrer_info.host.indexOf(engine.host) !== -1){ + session.search.engine = engine.name; + session.search.query = session.referrer_info.query[engine.query]; + session.search.terms = session.search.query ? session.search.query.split(" ") : null; + break; + } + } + if (session.search.engine === null && session.referrer_info.search.length > 1){ + for (i = 0; i < fallbacks.length; i++){ + var terms = session.referrer_info.query[fallbacks[i]]; + if (terms){ + session.search.engine = "Unknown"; + session.search.query = terms; session.search.terms = terms.split(" "); + break; + } + } + } + } else { + session.last_visit = new Date().getTime(); + session.visits++; + } + util.set_cookie(cookie, util.package_obj(session), expires); + return session; + }, + html5_location: function(){ + return function(callback){ + nav.geolocation.getCurrentPosition(function(pos){ + pos.source = 'html5'; + callback(pos); + }, function(err) { + if (options.gapi_location){ + modules.gapi_location()(callback); + } else { + callback({error: true, source: 'html5'}); } + }); + }; + }, + gapi_location: function(){ + return function(callback){ + var location = util.get_obj(options.location_cookie); + if (!location || location.source !== 'google'){ + win.gloader_ready = function() { + if ("google" in win){ + if (win.google.loader.ClientLocation){ + win.google.loader.ClientLocation.source = "google"; + callback(win.google.loader.ClientLocation); + } else { + callback({error: true, source: "google"}); + } + util.set_cookie( + options.location_cookie, + util.package_obj(win.google.loader.ClientLocation), + options.location_cookie_timeout * 60 * 60 * 1000); + }} + util.embed_script("https://www.google.com/jsapi?callback=gloader_ready"); + } else { + callback(location); + }} + }, + ipinfodb_location: function(api_key){ + return function (callback){ + var location_cookie = util.get_obj(options.location_cookie); + if (location_cookie && location_cookie.source === 'ipinfodb'){ callback(location_cookie); } + win.ipinfocb = function(data){ + if (data.statusCode === "OK"){ + data.source = "ipinfodb"; + util.set_cookie( + options.location_cookie, + util.package_obj(data), + options.location_cookie * 60 * 60 * 1000); + callback(data); + } else { + if (options.gapi_location){ return modules.gapi_location()(callback); } + else { callback({error: true, source: "ipinfodb", message: data.statusMessage}); } + }} + util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + api_key + "&format=json&callback=ipinfocb"); + }} + }; + + // Utilities + var util = { + parse_url: function(url_str){ + var a = doc.createElement("a"), query = {}; + a.href = url_str; query_str = a.search.substr(1); + // Disassemble query string + if (query_str != ''){ + var pairs = query_str.split("&"), i = 0, + length = pairs.length, parts; + for (; i < length; i++){ + parts = pairs[i].split("="); + if (parts.length === 2){ + query[parts[0]] = decodeURI(parts[1]); } + } + } + return { + host: a.host, + path: a.pathname, + protocol: a.protocol, + port: a.port === '' ? 80 : a.port, + search: a.search, + query: query } + }, + set_cookie: function(cname, value, expires, options){ // from jquery.cookie.js + if (!doc.cookie || !cname || !value){ return null; } + if (!options){ var options = {}; } + if (value === null || value === undefined){ expires = -1; } + if (expires){ options.expires = (new Date().getTime()) + expires; } + return (document.cookie = [ + encodeURIComponent(cname), '=', + encodeURIComponent(String(value)), + options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE + options.path ? '; path=' + options.path : '', + options.domain ? '; domain=' + options.domain : '', + (win.location && win.location.protocol === 'https:') ? '; secure' : '' + ].join('')); + }, + get_cookie: function(cookie_name, result){ // from jquery.cookie.js + return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookie_name) + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null; + }, + embed_script: function(url){ + var element = doc.createElement("script"); + element.type = "text/javascript"; + element.src = url; + doc.getElementsByTagName("body")[0].appendChild(element); + }, + package_obj: function (obj){ + obj.version = API_VERSION; + var ret = JSON.stringify(obj); + delete obj.version; return ret; + }, + get_obj: function(cookie_name){ + var obj; + try { obj = JSON.parse(util.get_cookie(cookie_name)); } catch(e){}; + if (obj && obj.version == API_VERSION){ + delete obj.version; return obj; + } + } + }; + + // JSON + var JSON = { + parse: (win.JSON && win.JSON.parse) || function(data){ + if (typeof data !== "string" || !data){ return null; } + return (new Function("return " + data))(); + }, + stringify: (win.JSON && win.JSON.stringify) || function(object){ + var type = typeof object; + if (type !== "object" || object === null) { + if (type === "string"){ return '"' + object + '"'; } + } else { + var k, v, json = [], + isArray = (object && object.constructor === Array); + for (k in object ) { + v = object[k]; type = typeof v; + if (type === "string") + v = '"' + v + '"'; + else if (type === "object" && v !== null) + v = this.stringify(v); + json.push((isArray ? "" : '"' + k + '":') + v); + } + return (isArray ? "[" : "{") + json.join(",") + (isArray ? "]" : "}"); + } } }; + + // Initialize SessionRunner + SessionRunner(); + +})(window, document, navigator); diff --git a/session-0.4.min.js b/session-0.4.min.js new file mode 100644 index 0000000..8aabc62 --- /dev/null +++ b/session-0.4.min.js @@ -0,0 +1,8 @@ +/** + * session.js 0.4.1 + * (c) 2012 Iain, CodeJoust + * session.js is freely distributable under the MIT license. + * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. + * This version uses google's jsapi library for location services. + * For details, see: https://github.com/codejoust/session.js + */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){if(a.session&&a.session.options)for(option in a.session.options)e[option]=a.session.options[option];this.modules={api_version:d,locale:h.locale(),current_session:h.session(),original_session:h.session(e.session_cookie,e.session_timeout*24*60*60*1e3),browser:h.browser(),plugins:h.plugins(),time:h.time(),device:h.device()},e.use_html5_location?this.modules.location=h.html5_location():e.ipinfodb_key?this.modules.location=h.ipinfodb_location(e.ipinfodb_key):e.gapi_location&&(this.modules.location=h.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var c=0,f,g,i=this,j=function(){c===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{c++,f(function(a){i.modules[k]=a,c--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},g={detect:function(){return{browser:this.search(this.data.browser),version:this.search(c.userAgent)||this.search(c.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k1)for(k=0;k Date: Mon, 9 Jan 2012 10:07:15 -0500 Subject: [PATCH 19/29] Updating script --- session.js | 20 +++++++------------- session.min.js | 2 +- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/session.js b/session.js index d397b70..f66d87f 100644 --- a/session.js +++ b/session.js @@ -52,7 +52,7 @@ options.session_timeout * 24 * 60 * 60 * 1000), browser: modules.browser(), plugins: modules.plugins(), - time: modules.time(), // uses callback + time: modules.time(), device: modules.device() }; // Location switch @@ -160,18 +160,12 @@ return browser.detect(); }, time: function(){ - // wrapping in a callback to catch failures... - try { - var d = new Date('Sat, 07 Jan 2012 04:10:00 +0000'); - d = d.toString(); - d = d.match(/\(([^]+)\)/)[1]; - // split date and grab timezone estimation. - // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ - var d1 = new Date(), d2 = new Date(); - d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); - return({timezone: d, tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); - // Gives a browser estimation, not guaranteed to be correct. - } catch (e){ return {err: true, msg: e}; } + // split date and grab timezone estimation. + // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ + var d1 = new Date(), d2 = new Date(); + d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); + return({tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); + // Gives a browser estimation, not guaranteed to be correct. }, locale: function() { var lang = ( diff --git a/session.min.js b/session.min.js index 8aabc62..1021418 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){if(a.session&&a.session.options)for(option in a.session.options)e[option]=a.session.options[option];this.modules={api_version:d,locale:h.locale(),current_session:h.session(),original_session:h.session(e.session_cookie,e.session_timeout*24*60*60*1e3),browser:h.browser(),plugins:h.plugins(),time:h.time(),device:h.device()},e.use_html5_location?this.modules.location=h.html5_location():e.ipinfodb_key?this.modules.location=h.ipinfodb_location(e.ipinfodb_key):e.gapi_location&&(this.modules.location=h.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var c=0,f,g,i=this,j=function(){c===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{c++,f(function(a){i.modules[k]=a,c--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},g={detect:function(){return{browser:this.search(this.data.browser),version:this.search(c.userAgent)||this.search(c.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Mon, 9 Jan 2012 11:54:28 -0500 Subject: [PATCH 20/29] Fixes, pushing up to session.js --- session.js | 20 +++++++++++++------- session.min.js | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/session.js b/session.js index f66d87f..d397b70 100644 --- a/session.js +++ b/session.js @@ -52,7 +52,7 @@ options.session_timeout * 24 * 60 * 60 * 1000), browser: modules.browser(), plugins: modules.plugins(), - time: modules.time(), + time: modules.time(), // uses callback device: modules.device() }; // Location switch @@ -160,12 +160,18 @@ return browser.detect(); }, time: function(){ - // split date and grab timezone estimation. - // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ - var d1 = new Date(), d2 = new Date(); - d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); - return({tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); - // Gives a browser estimation, not guaranteed to be correct. + // wrapping in a callback to catch failures... + try { + var d = new Date('Sat, 07 Jan 2012 04:10:00 +0000'); + d = d.toString(); + d = d.match(/\(([^]+)\)/)[1]; + // split date and grab timezone estimation. + // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ + var d1 = new Date(), d2 = new Date(); + d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); + return({timezone: d, tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); + // Gives a browser estimation, not guaranteed to be correct. + } catch (e){ return {err: true, msg: e}; } }, locale: function() { var lang = ( diff --git a/session.min.js b/session.min.js index 1021418..8aabc62 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){if(a.session&&a.session.options)for(option in a.session.options)e[option]=a.session.options[option];this.modules={api_version:d,locale:h.locale(),current_session:h.session(),original_session:h.session(e.session_cookie,e.session_timeout*24*60*60*1e3),browser:h.browser(),plugins:h.plugins(),time:h.time(),device:h.device()},e.use_html5_location?this.modules.location=h.html5_location():e.ipinfodb_key?this.modules.location=h.ipinfodb_location(e.ipinfodb_key):e.gapi_location&&(this.modules.location=h.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var c=0,f,g,i=this,j=function(){c===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{c++,f(function(a){i.modules[k]=a,c--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},g={detect:function(){return{browser:this.search(this.data.browser),version:this.search(c.userAgent)||this.search(c.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Mon, 9 Jan 2012 20:46:38 -0500 Subject: [PATCH 21/29] Updating demo with fixed blocking api --- session-0.4.js | 60 +++++++++++++++++++++++----------------------- session-0.4.min.js | 2 +- session.js | 60 +++++++++++++++++++++++----------------------- session.min.js | 2 +- 4 files changed, 62 insertions(+), 62 deletions(-) diff --git a/session-0.4.js b/session-0.4.js index d397b70..b2befb3 100644 --- a/session-0.4.js +++ b/session-0.4.js @@ -35,15 +35,23 @@ // Session object var SessionRunner = function(){ + // Helper for querying. + // Usage: session.current_session.referrer_info.hostname.contains(['github.com','news.ycombinator.com']) + String.prototype.contains = function(other_str){ + if (typeof(other_str) === 'string'){ + return (this.indexOf(other_str) !== -1); } + for (var i = 0; i < other_str.length; i++){ + if (this.indexOf(other_str[i]) !== -1){ return true; } } + return false; } // Merge options - if(win.session && win.session.options) { + if (win.session && win.session.options) { for (option in win.session.options){ options[option] = win.session.options[option]; } } // Modules to run // If the module has arguments, // it _needs_ to return a callback function. - this.modules = { + var unloaded_modules = { api_version: API_VERSION, locale: modules.locale(), current_session: modules.session(), @@ -52,50 +60,48 @@ options.session_timeout * 24 * 60 * 60 * 1000), browser: modules.browser(), plugins: modules.plugins(), - time: modules.time(), // uses callback + time: modules.time(), device: modules.device() }; // Location switch if (options.use_html5_location){ - this.modules.location = modules.html5_location(); + unloaded_modules.location = modules.html5_location(); } else if (options.ipinfodb_key){ - this.modules.location = modules.ipinfodb_location(options.ipinfodb_key); + unloaded_modules.location = modules.ipinfodb_location(options.ipinfodb_key); } else if (options.gapi_location){ - this.modules.location = modules.gapi_location(); + unloaded_modules.location = modules.gapi_location(); } // Cache win.session.start if (win.session && win.session.start){ var start = win.session.start; } // Set up checking, if all modules are ready - var asynchs = 0, module, result, self = this, + var asynchs = 0, module, result, check_asynch = function(){ if (asynchs === 0){ - // Map over results - win.session = self.modules; // Run start calback - if (start){ start(self.modules); } + if (start){ start(win.session); } } }; + win.session = {}; // Run asynchronous methods - for (var name in this.modules){ - module = self.modules[name]; - if(typeof module === "function"){ + for (var name in unloaded_modules){ + module = unloaded_modules[name]; + if (typeof module === "function"){ try { - asynchs++; module(function(data){ - self.modules[name] = data; + win.session[name] = data; asynchs--; check_asynch(); }); + asynchs++; } catch(err){ if (win.console && typeof(console.log) === "function"){ console.log(err); } } } else { - self.modules[name] = module; - } - } + win.session[name] = module; + } } check_asynch(); }; @@ -160,18 +166,12 @@ return browser.detect(); }, time: function(){ - // wrapping in a callback to catch failures... - try { - var d = new Date('Sat, 07 Jan 2012 04:10:00 +0000'); - d = d.toString(); - d = d.match(/\(([^]+)\)/)[1]; - // split date and grab timezone estimation. - // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ - var d1 = new Date(), d2 = new Date(); - d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); - return({timezone: d, tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); - // Gives a browser estimation, not guaranteed to be correct. - } catch (e){ return {err: true, msg: e}; } + // split date and grab timezone estimation. + // timezone estimation: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/ + var d1 = new Date(), d2 = new Date(); + d1.setMonth(0); d1.setDate(1); d2.setMonth(6); d2.setDate(1); + return({tz_offset: -(new Date().getTimezoneOffset()) / 60, observes_dst: (d1.getTimezoneOffset() !== d2.getTimezoneOffset()) }); + // Gives a browser estimation, not guaranteed to be correct. }, locale: function() { var lang = ( diff --git a/session-0.4.min.js b/session-0.4.min.js index 8aabc62..346e035 100644 --- a/session-0.4.min.js +++ b/session-0.4.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){if(a.session&&a.session.options)for(option in a.session.options)e[option]=a.session.options[option];this.modules={api_version:d,locale:h.locale(),current_session:h.session(),original_session:h.session(e.session_cookie,e.session_timeout*24*60*60*1e3),browser:h.browser(),plugins:h.plugins(),time:h.time(),device:h.device()},e.use_html5_location?this.modules.location=h.html5_location():e.ipinfodb_key?this.modules.location=h.ipinfodb_location(e.ipinfodb_key):e.gapi_location&&(this.modules.location=h.gapi_location());if(a.session&&a.session.start)var b=a.session.start;var c=0,f,g,i=this,j=function(){c===0&&(a.session=i.modules,b&&b(i.modules))};for(var k in this.modules){f=i.modules[k];if(typeof f=="function")try{c++,f(function(a){i.modules[k]=a,c--,j()})}catch(l){a.console&&typeof console.log=="function"&&console.log(l)}else i.modules[k]=f}j()},g={detect:function(){return{browser:this.search(this.data.browser),version:this.search(c.userAgent)||this.search(c.appVersion),os:this.search(this.data.os)}},search:function(a){if(typeof a!="object"){var e=a.indexOf(this.version_string);if(e==-1)return;return parseFloat(a.substr(e+this.version_string.length+1))}for(var b=0;b1)for(k=0;k1)for(k=0;k1)for(k=0;k1)for(k=0;k Date: Mon, 9 Jan 2012 23:48:20 -0500 Subject: [PATCH 22/29] Adding API example --- example.html | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 example.html diff --git a/example.html b/example.html new file mode 100644 index 0000000..2488148 --- /dev/null +++ b/example.html @@ -0,0 +1,61 @@ + + + + + Session.js example usage + + +

Session.js Example Usage:

+
Info:
+
loading motd...
+

+ View Example Source +

+
+

About

+

Session.js is a javascript library that lets you customize your page according to the current session.

+

Such an example would be autosuggesting location box values, or timezones, based on either location or system settings returned by javascript.

+

For more information, check out the github project page or the API demo.

+
+ + + + + \ No newline at end of file From 2769bab382044b50330646043e047d3791893f67 Mon Sep 17 00:00:00 2001 From: Iain Nash Date: Wed, 11 Jan 2012 20:31:05 -0500 Subject: [PATCH 23/29] Updating script (Fixes #12) --- session.js | 10 +++++----- session.min.js | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/session.js b/session.js index b2befb3..29e682e 100644 --- a/session.js +++ b/session.js @@ -77,7 +77,8 @@ } // Set up checking, if all modules are ready var asynchs = 0, module, result, - check_asynch = function(){ + check_asynch = function(deinc){ + if (deinc){ asynchs--; } if (asynchs === 0){ // Run start calback if (start){ start(win.session); } @@ -91,13 +92,12 @@ try { module(function(data){ win.session[name] = data; - asynchs--; - check_asynch(); + check_asynch(true); }); asynchs++; } catch(err){ if (win.console && typeof(console.log) === "function"){ - console.log(err); } + console.log(err); check_asynch(true); } } } else { win.session[name] = module; @@ -356,7 +356,7 @@ encodeURIComponent(cname), '=', encodeURIComponent(String(value)), options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE - options.path ? '; path=' + options.path : '', + options.path ? '; path=' + options.path : '/', options.domain ? '; domain=' + options.domain : '', (win.location && win.location.protocol === 'https:') ? '; secure' : '' ].join('')); diff --git a/session.min.js b/session.min.js index 346e035..dbb37f0 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){String.prototype.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Wed, 11 Jan 2012 20:35:48 -0500 Subject: [PATCH 24/29] Updating session.js --- session.js | 2 +- session.min.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/session.js b/session.js index 29e682e..0aec7d3 100644 --- a/session.js +++ b/session.js @@ -356,7 +356,7 @@ encodeURIComponent(cname), '=', encodeURIComponent(String(value)), options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE - options.path ? '; path=' + options.path : '/', + '; path=' + options.path ? options.path : '/', options.domain ? '; domain=' + options.domain : '', (win.location && win.location.protocol === 'https:') ? '; secure' : '' ].join('')); diff --git a/session.min.js b/session.min.js index dbb37f0..b64ba10 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){String.prototype.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Wed, 11 Jan 2012 20:44:41 -0500 Subject: [PATCH 25/29] Updating demo --- session.js | 4 ++-- session.min.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/session.js b/session.js index 0aec7d3..0b8534e 100644 --- a/session.js +++ b/session.js @@ -348,7 +348,7 @@ query: query } }, set_cookie: function(cname, value, expires, options){ // from jquery.cookie.js - if (!doc.cookie || !cname || !value){ return null; } + if (!cname){ return null; } if (!options){ var options = {}; } if (value === null || value === undefined){ expires = -1; } if (expires){ options.expires = (new Date().getTime()) + expires; } @@ -356,7 +356,7 @@ encodeURIComponent(cname), '=', encodeURIComponent(String(value)), options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE - '; path=' + options.path ? options.path : '/', + '; path=' + (options.path ? options.path : '/'), options.domain ? '; domain=' + options.domain : '', (win.location && win.location.protocol === 'https:') ? '; secure' : '' ].join('')); diff --git a/session.min.js b/session.min.js index b64ba10..1ae942b 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){String.prototype.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Fri, 4 May 2012 17:43:29 -0400 Subject: [PATCH 26/29] updating gh-pages with contains changes --- example.html | 8 +++--- session.js | 69 ++++++++++++++++++++++++++++---------------------- session.min.js | 2 +- 3 files changed, 44 insertions(+), 35 deletions(-) diff --git a/example.html b/example.html index 2488148..ed51501 100644 --- a/example.html +++ b/example.html @@ -33,11 +33,11 @@

About

if (session.location){ add_msg('Hi again from ' + session.location.address.city + '.'); } else { add_msg('Welcome back!'); } } else { - if (session.current_session.referrer_info.host.contains('facebook.com')){ + if (session.contains(session.current_session.referrer_info.host,'facebook.com')){ add_msg('Hi there from '+ session.location.address.city +'. How about liking us on facebook?'); - } else if (session.current_session.referrer_info.host.contains('github.com')){ + } else if (session.contains(session.current_session.referrer_info.host, 'github.com')){ add_msg('How about watching us on github?'); - } else if (session.current_session.referrer_info.host.contains('twitter.com')){ + } else if (session.contains(session.current_session.referrer_info.host, 'twitter.com')){ add_msg('Hi there from twitter!'); } else if (session.current_session.search.engine){ add_msg('Did you find what you were looking for from ' + session.current_session.search.engine + '?'); @@ -58,4 +58,4 @@

About

} - \ No newline at end of file + diff --git a/session.js b/session.js index 0b8534e..707bf67 100644 --- a/session.js +++ b/session.js @@ -6,10 +6,9 @@ * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js */ -(function(win, doc, nav){ +var session_fetch = (function(win, doc, nav){ // Changing the API Version invalidates olde cookies with previous api version tags. var API_VERSION = 0.4; - // Settings: defaults var options = { // Use the HTML5 Geolocation API @@ -32,12 +31,13 @@ // Session cookie name (set blank to disable cookie) session_cookie: "first_session" }; - + // Session object var SessionRunner = function(){ + win.session = {}; // Helper for querying. // Usage: session.current_session.referrer_info.hostname.contains(['github.com','news.ycombinator.com']) - String.prototype.contains = function(other_str){ + win.session.contains = function(other_str){ if (typeof(other_str) === 'string'){ return (this.indexOf(other_str) !== -1); } for (var i = 0; i < other_str.length; i++){ @@ -104,8 +104,8 @@ } } check_asynch(); }; - - + + // Browser (and OS) detection var browser = { detect: function(){ @@ -155,12 +155,12 @@ { string: nav.platform, subString: "Win", identity: "Windows" }, { string: nav.platform, subString: "Mac", identity: "Mac" }, { string: nav.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, - { string: nav.userAgent, subString: "iPad", identitiy: "iPad" }, - { string: nav.platform, subString: "Linux", identity: "Linux" }, - { string: nav.userAgent, subString: "Android", identity: "Android" } + { string: nav.userAgent, subString: "iPad", identity: "iPad" }, + { string: nav.userAgent, subString: "Android", identity: "Android" }, + { string: nav.platform, subString: "Linux", identity: "Linux" } ]} }; - + var modules = { browser: function(){ return browser.detect(); @@ -174,12 +174,12 @@ // Gives a browser estimation, not guaranteed to be correct. }, locale: function() { - var lang = ( + var lang = (( nav.language || nav.browserLanguage || nav.systemLanguage || nav.userLanguage - ).split("-"); + ) || '').split("-"); if (lang.length == 2){ return { country: lang[1].toLowerCase(), lang: lang[0].toLowerCase() }; } else if (lang) { @@ -189,19 +189,17 @@ device: function() { var device = { screen: { - width: screen.width, - height: screen.height + width: win.screen.width, + height: win.screen.height } }; - var html = doc.documentElement, - body = doc.getElementsByTagName("body")[0]; device.viewport = { - width: win.innerWidth || html.clientWidth || body.clientWidth, - height: win.innerHeight || html.clientHeight || body.clientHeight + width: win.innerWidth || doc.body.clientWidth || doc.documentElement.clientWidth, + height: win.innerHeight || doc.body.clientHeight || doc.documentElement.clientHeight }; device.is_tablet = !!nav.userAgent.match(/(iPad|SCH-I800|xoom|kindle)/i); - device.is_phone = !device.isTablet && !!nav.userAgent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i); - device.is_mobile = (device.is_tablet || device.is_phone); + device.is_phone = !device.is_tablet && !!nav.userAgent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i); + device.is_mobile = device.is_tablet || device.is_phone; return device; }, plugins: function(){ @@ -221,7 +219,7 @@ silverlight: check_plugin("silverlight"), java: check_plugin("java"), quicktime: check_plugin("quicktime") - }; + }; }, session: function (cookie, expires){ var session = util.get_obj(cookie); @@ -260,11 +258,13 @@ session.search.query = terms; session.search.terms = terms.split(" "); break; } - } + } } } else { + session.prev_visit = session.last_visit; session.last_visit = new Date().getTime(); session.visits++; + session.time_since_last_visit = session.last_visit - session.prev_visit; } util.set_cookie(cookie, util.package_obj(session), expires); return session; @@ -323,7 +323,7 @@ util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + api_key + "&format=json&callback=ipinfocb"); }} }; - + // Utilities var util = { parse_url: function(url_str){ @@ -352,7 +352,7 @@ if (!options){ var options = {}; } if (value === null || value === undefined){ expires = -1; } if (expires){ options.expires = (new Date().getTime()) + expires; } - return (document.cookie = [ + return (doc.cookie = [ encodeURIComponent(cname), '=', encodeURIComponent(String(value)), options.expires ? '; expires=' + new Date(options.expires).toUTCString() : '', // use expires attribute, max-age is not supported by IE @@ -362,7 +362,7 @@ ].join('')); }, get_cookie: function(cookie_name, result){ // from jquery.cookie.js - return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookie_name) + '=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null; + return (result = new RegExp('(?:^|; )' + encodeURIComponent(cookie_name) + '=([^;]*)').exec(doc.cookie)) ? decodeURIComponent(result[1]) : null; }, embed_script: function(url){ var element = doc.createElement("script"); @@ -371,9 +371,12 @@ doc.getElementsByTagName("body")[0].appendChild(element); }, package_obj: function (obj){ - obj.version = API_VERSION; - var ret = JSON.stringify(obj); - delete obj.version; return ret; + if(obj) { + obj.version = API_VERSION; + var ret = JSON.stringify(obj); + delete obj.version; + return ret; + } }, get_obj: function(cookie_name){ var obj; @@ -383,7 +386,7 @@ } } }; - + // JSON var JSON = { parse: (win.JSON && win.JSON.parse) || function(data){ @@ -411,4 +414,10 @@ // Initialize SessionRunner SessionRunner(); -})(window, document, navigator); +}); +// Switch for testing purposes. +if (typeof(window.exports) === 'undefined'){ + session_fetch(window, document, navigator); +} else { + window.exports.session = session_fetch; +} diff --git a/session.min.js b/session.min.js index 1ae942b..dfad560 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){String.prototype.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Sun, 17 Jun 2012 09:13:23 -0400 Subject: [PATCH 27/29] updating gh-pages repo --- session.js | 2 +- session.min.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/session.js b/session.js index 707bf67..9dc7aad 100644 --- a/session.js +++ b/session.js @@ -34,7 +34,7 @@ var session_fetch = (function(win, doc, nav){ // Session object var SessionRunner = function(){ - win.session = {}; + win.session = win.session || {}; // Helper for querying. // Usage: session.current_session.referrer_info.hostname.contains(['github.com','news.ycombinator.com']) win.session.contains = function(other_str){ diff --git a/session.min.js b/session.min.js index dfad560..d008d80 100644 --- a/session.min.js +++ b/session.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */var session_fetch=function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){a.session={},a.session.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(k=0;k Date: Thu, 9 Aug 2012 14:22:40 -0700 Subject: [PATCH 28/29] Fixing IE Bug --- session-0.4.js | 4 ++-- session-0.4.min.js | 2 +- session.js | 4 ++-- session.min.js | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/session-0.4.js b/session-0.4.js index b2befb3..b618452 100644 --- a/session-0.4.js +++ b/session-0.4.js @@ -196,8 +196,8 @@ var html = doc.documentElement, body = doc.getElementsByTagName("body")[0]; device.viewport = { - width: win.innerWidth || html.clientWidth || body.clientWidth, - height: win.innerHeight || html.clientHeight || body.clientHeight + width: win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth, + height: win.innerHeight || doc.documentElement.clientHeight || doc.body.clientHeight }; device.is_tablet = !!nav.userAgent.match(/(iPad|SCH-I800|xoom|kindle)/i); device.is_phone = !device.isTablet && !!nav.userAgent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i); diff --git a/session-0.4.min.js b/session-0.4.min.js index 346e035..089cee5 100644 --- a/session-0.4.min.js +++ b/session-0.4.min.js @@ -5,4 +5,4 @@ * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. * This version uses google's jsapi library for location services. * For details, see: https://github.com/codejoust/session.js - */(function(a,b,c){var d=.4,e={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},f=function(){String.prototype.contains=function(a){if(typeof a=="string")return this.indexOf(a)!==-1;for(var b=0;b1)for(k=0;k1)for(l=0;l1)for(k=0;k1)for(l=0;l Date: Mon, 2 Dec 2013 08:51:18 -0800 Subject: [PATCH 29/29] Session update pages --- session.js | 80 ++++++++++++++++++++++++++++++++++++++------------ session.min.js | 9 +----- 2 files changed, 63 insertions(+), 26 deletions(-) diff --git a/session.js b/session.js index 190654b..4a9244a 100644 --- a/session.js +++ b/session.js @@ -7,6 +7,7 @@ * For details, see: https://github.com/codejoust/session.js */ var session_fetch = (function(win, doc, nav){ + 'use strict'; // Changing the API Version invalidates olde cookies with previous api version tags. var API_VERSION = 0.4; // Settings: defaults @@ -29,7 +30,9 @@ var session_fetch = (function(win, doc, nav){ // Session expiration in days session_timeout: 32, // Session cookie name (set blank to disable cookie) - session_cookie: "first_session" + session_cookie: "first_session", + get_object: null, set_object: null // used for cookie session adaptors + // if null, will be reset to use cookies by default. }; // Session object @@ -42,10 +45,10 @@ var session_fetch = (function(win, doc, nav){ return (this.indexOf(other_str) !== -1); } for (var i = 0; i < other_str.length; i++){ if (this.indexOf(other_str[i]) !== -1){ return true; } } - return false; } + return false; }; // Merge options if (win.session && win.session.options) { - for (option in win.session.options){ + for (var option in win.session.options){ options[option] = win.session.options[option]; } } // Modules to run @@ -109,11 +112,22 @@ var session_fetch = (function(win, doc, nav){ // Browser (and OS) detection var browser = { detect: function(){ - return { + var ret = { browser: this.search(this.data.browser), version: this.search(nav.userAgent) || this.search(nav.appVersion), os: this.search(this.data.os) - } }, + }; + if (ret.os=='Linux'){ + var distros = ['CentOS','Debian','Fedora','Gentoo','Mandriva','Mageia','Red Hat','Slackware','SUSE','Turbolinux','Ubuntu']; + for (var i = 0; i < distros.length;i++){ + if (nav.useragent.toLowerCase().match(distros[i].toLowerCase())){ + ret.distro = distros[i]; + break; + } + } + } + return ret; + }, search: function(data) { if (typeof data === "object"){ // search for string match @@ -213,9 +227,20 @@ var session_fetch = (function(win, doc, nav){ } } return false; } return false; + }; + var check_activex_flash = function(versions){ + var found = true; + for (var i = 0; i < versions.length; i++){ + try { + var obj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash" + versions[i]) + , found = !0; + } catch (e){ /* nil */ } + if (found) return true; + } + return false; } return { - flash: check_plugin("flash"), + flash: check_plugin("flash") || check_activex_flash(['.7','.6','']), silverlight: check_plugin("silverlight"), java: check_plugin("java"), quicktime: check_plugin("quicktime") @@ -266,7 +291,7 @@ var session_fetch = (function(win, doc, nav){ session.visits++; session.time_since_last_visit = session.last_visit - session.prev_visit; } - util.set_cookie(cookie, util.package_obj(session), expires); + util.set_obj(cookie, session, expires); return session; }, html5_location: function(){ @@ -294,33 +319,43 @@ var session_fetch = (function(win, doc, nav){ } else { callback({error: true, source: "google"}); } - util.set_cookie( + util.set_obj( options.location_cookie, - util.package_obj(win.google.loader.ClientLocation), + win.google.loader.ClientLocation, options.location_cookie_timeout * 60 * 60 * 1000); - }} + }}; util.embed_script("https://www.google.com/jsapi?callback=gloader_ready"); } else { callback(location); - }} + }}; + }, + architecture: function(){ + var arch = n.userAgent.match(/x86_64|Win64|WOW64|x86-64|x64\;|AMD64|amd64/) || + (n.cpuClass === 'x64') ? 'x64' : 'x86'; + return { + arch: arch, + is_x64: arch == 'x64', + is_x86: arch == 'x68' + } }, ipinfodb_location: function(api_key){ return function (callback){ var location_cookie = util.get_obj(options.location_cookie); - if (location_cookie && location_cookie.source === 'ipinfodb'){ callback(location_cookie); } + if (!location_cookie && location_cookie.source === 'ipinfodb'){ win.ipinfocb = function(data){ if (data.statusCode === "OK"){ data.source = "ipinfodb"; - util.set_cookie( + util.set_obj( options.location_cookie, - util.package_obj(data), + data, options.location_cookie * 60 * 60 * 1000); callback(data); } else { if (options.gapi_location){ return modules.gapi_location()(callback); } else { callback({error: true, source: "ipinfodb", message: data.statusMessage}); } - }} + }}; util.embed_script("http://api.ipinfodb.com/v3/ip-city/?key=" + api_key + "&format=json&callback=ipinfocb"); + } else { callback(location_cookie); } }} }; @@ -328,7 +363,7 @@ var session_fetch = (function(win, doc, nav){ var util = { parse_url: function(url_str){ var a = doc.createElement("a"), query = {}; - a.href = url_str; query_str = a.search.substr(1); + a.href = url_str; var query_str = a.search.substr(1); // Disassemble query string if (query_str != ''){ var pairs = query_str.split("&"), i = 0, @@ -349,7 +384,7 @@ var session_fetch = (function(win, doc, nav){ }, set_cookie: function(cname, value, expires, options){ // from jquery.cookie.js if (!cname){ return null; } - if (!options){ var options = {}; } + if (!options){ options = {}; } if (value === null || value === undefined){ expires = -1; } if (expires){ options.expires = (new Date().getTime()) + expires; } return (doc.cookie = [ @@ -378,15 +413,24 @@ var session_fetch = (function(win, doc, nav){ return ret; } }, + set_obj: function(cname, value, expires, options){ + util.set_cookie(cname, util.package_obj(value), expires, options); + }, get_obj: function(cookie_name){ var obj; - try { obj = JSON.parse(util.get_cookie(cookie_name)); } catch(e){}; + try { obj = JSON.parse(util.get_cookie(cookie_name)); } catch(e){} if (obj && obj.version == API_VERSION){ delete obj.version; return obj; } } }; + // cookie options override + if (options.get_object != null){ + util.get_obj = options['get_object']; } + if (options.set_object != null){ + util.set_obj = options['set_object']; } + // JSON var JSON = { parse: (win.JSON && win.JSON.parse) || function(data){ diff --git a/session.min.js b/session.min.js index 3ab6e9b..85b992c 100644 --- a/session.min.js +++ b/session.min.js @@ -1,8 +1 @@ -/** - * session.js 0.4.1 - * (c) 2012 Iain, CodeJoust - * session.js is freely distributable under the MIT license. - * Portions of session.js are inspired or borrowed from Underscore.js, and quirksmode.org demo javascript. - * This version uses google's jsapi library for location services. - * For details, see: https://github.com/codejoust/session.js - */var session_fetch=function(e,t,n){var r=.4,i={use_html5_location:!1,ipinfodb_key:!1,gapi_location:!0,location_cookie:"location",location_cookie_timeout:5,session_timeout:32,session_cookie:"first_session"},s=function(){e.session=e.session||{},e.session.contains=function(e){if(typeof e=="string")return this.indexOf(e)!==-1;for(var t=0;t1)for(l=0;l1){for(i=0;i