/*
@collection
Sorry for my bad Javascript ^_^
*/
m = {
key: 'history', //key for local storage
ls: window.localStorage, //local alias
/* Clear stored data */
clearData: function() {
m.ls.removeItem( m.key );
m.ls.setItem( m.key, "[]" ); //initialize our var' as JSON's array
},
/* Get stored data helper */
get: function() {
if ( m.ls.getItem( m.key ) == null ) { //var' isn't initialized
m.ls.setItem( m.key, "[]" );
}
/* Local storage provides only string saving. Using JSON for [un]serializing arrays */
return JSON.parse( m.ls.getItem( m.key ) );
},
/* Set stored data helper */
set: function( v ) {
m.ls.setItem(
m.key,
JSON.stringify( (m.get()).concat( [v] ) ) //concat prev' and present data, JSON it
);
},
/* Callback for event listener */
callbackTabs: function( id, i, tab ) {
if ( tab.status == 'complete' ) { //event fires 2 times: "loading" and "complete" states
m.set( { //store that
date: m.date(),
favIcon: tab.favIconUrl || '',
url: tab.url || '',
title: tab.title || '',
incognito: tab.incognito
} );
}
},
/* Ugly date format helper */
date: function() {
d = new Date();
return '' + (
( d.getDate() > 9 ? d.getDate() : '0' + d.getDate() ) + ' ' +
['January','February','March','April','May','June','July','August',
'September','October','November','December'][d.getMonth()] +
' ' + d.getFullYear() + ', ' +
( d.getHours() > 9 ? d.getHours() : '0' + d.getHours() ) + ':' +
( d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes() ) + ':' +
( d.getSeconds() > 9 ? d.getSeconds() : '0' + d.getSeconds() )
);
},
/* $(id) getter */
$: function( id ) {
return document.getElementById( id );
},
/* Helper for decomposition of an URL */
parseURL: function( url ) {
var a = document.createElement('a');
a.href = url;
//some extra parts are commented, we don't need 'em
return {
/* source: url,
protocol: a.protocol.replace(':',''), */
host: a.hostname,
/* port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''), */
path: a.pathname.replace(/^([^/])/,'/$1')/* ,
relative: (a.href.match(/tp://[^/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^//,'').split('/') */
};
},
/* Displaying history helper. History iterator */
displayData: function() {
var html = ''; //dirty working with DOM
(m.get()).forEach( function( v ) {
p = m.parseURL( v.url );
html += '<li><span>' + v.date + '</span> ' + ( v.incognito ? '<strong>incognito mode</strong> ' : '')
+ '<a href="' + v.url + '"><img src="'
+ ( v.favIcon ? v.favIcon : ('http://www.google.com/s2/favicons?domain=' + p.host) ) + '"/>'
+ ( v.title ? v.title : ((p.host + p.path ).substr( 0, 80 )) ) + '</a></li>';
});
m.$( 'putHere' ).innerHTML = html;
return false;
}
};
/* Add a tabs listener */
chrome.tabs.onUpdated.addListener( m.callbackTabs );