Skip to content

Instantly share code, notes, and snippets.

@sineausr931
Created July 19, 2021 21:15
Show Gist options
  • Save sineausr931/f484d1a39be4fda6a6d8c86b49945e8e to your computer and use it in GitHub Desktop.
Save sineausr931/f484d1a39be4fda6a6d8c86b49945e8e to your computer and use it in GitHub Desktop.
Using promises with chrome extension history API
var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
var searchEpoch = microsecondsPerWeek * 52;
var oneYearAgo = (new Date).getTime() - searchEpoch;
// Chrome history API does not yet support promises, only callback
// So, wrap the chrome.history.search in a promise of our own
function chromeHistorySearchAsync() {
console.log("beginning query");
return new Promise(function(resolve, reject) {
console.log("inside promise");
chrome.history.search({'text': '', 'startTime': oneYearAgo, 'maxResults': 100}, (historyItems) => {
console.log(`query complete, ${historyItems.length} matches found`);
resolve(historyItems);
});
});
}
chromeHistorySearchAsync().then((historyItems) => {
var domainNames = new Map;
for (var i = 0; i < historyItems.length; i++) {
var url = historyItems[i].url;
// console.log(`DEBUG: url = ${url}`)
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var name = matches && matches[1];
// console.log(`DEBUG: name = ${name}`)
// Note: chrome*:// urls will result in a null name
if (!domainNames.has(name)) {
domainNames.set(name, {"visits": 1})
} else {
domainNames.get(name).visits += 1;
}
}
return domainNames;
}).then((domainNames) => {
domainNames.forEach((value, key) => {
console.log(`"${key}" : ${value.visits}`);
});
});
/** Sample output:
beginning query
inside promise
query complete, 100 matches found
"null" : 4
"www.google.com" : 28
"www.instagram.com" : 2
"gist.github.com" : 5
"mail.google.com" : 2
"twitter.com" : 7
"www.imdb.com" : 1
"developer.mozilla.org" : 10
"stackoverflow.com" : 1
"developers.google.com" : 1
"bluebirdjs.com" : 3
"www.espn.com" : 1
"vega.github.io" : 1
"shop.blueorigin.com" : 2
"www.blueorigin.com" : 2
"imgur.com" : 6
"help.imgur.com" : 1
"www.libpng.org" : 1
"www.loc.gov" : 1
"en.wikipedia.org" : 1
"github.com" : 12
"www.npmjs.com" : 3
"www.kaspersky.com" : 1
"securelist.com" : 2
"superuser.com" : 1
"yarnpkg.com" : 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment