Skip to content

Instantly share code, notes, and snippets.

@raykendo
Last active November 24, 2015 20:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raykendo/c938604387f788fdf3c8 to your computer and use it in GitHub Desktop.
Save raykendo/c938604387f788fdf3c8 to your computer and use it in GitHub Desktop.
Dojo time stamp browser plugins
/**
* Gets a time stamp out of either localStorage, or a cookie session, if those are available.
* Use in conjunction with SetTimeStamp module.
* @module GetTimeStamp
* @param {string} id - string id you want to use to retrieve a time stamp from the browser
* @returns {Date} - Date of the last time stamp
*/
define(["dojo/cookie"], function (cookie) {
return {
load: function (id, require, callback) {
// localStorage test courtesy of Mathtias Bynens: https://mathiasbynens.be/notes/localstorage-pattern
var storage, fail, uid, d, ms;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (exception) {
if (cookie.isSupported()) {
storage = {
getItem: function (item) { return cookie(item); }
};
}
} finally {
d = new Date(0);
if (storage) {
ms = storage.getItem(id);
if (ms && !isNaN(ms)) {
d.setUTCSeconds(parseInt(ms, 10));
}
}
callback(d);
}
}
}
});
/**
* Stores a time stamp in either localStorage or a cookie session, if either of those is available.
* Use in conjunction with GetTimeStamp module.
* @module SetTimeStamp
* @param {string} id - string id you want to use to retrieve a time stamp from the browser
* @returns {Date} - Date the timestamp was added
*/
define(["dojo/cookie", "dojo/json"], function (cookie, json) {
return {
load: function (id, require, callback) {
// localStorage test courtesy of Mathtias Bynens: https://mathiasbynens.be/notes/localstorage-pattern
var storage, fail, uid, d;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (exception) {
if (cookie.isSupported()) {
storage = {
setItem: function (name, value) { cookie(name, value, { expires: 365 }); }
};
}
} finally {
d = new Date();
if (storage) {
storage.setItem(id, json.stringify(d.getTime()/1000));
} else {
console.log("I won't remember this.");
}
callback(d);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment