Last active
November 20, 2018 11:00
-
-
Save femioladeji/1e6dc4a096ebcd35c48c945d78c1e5fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const urls = [ | |
'*://*.facebook.com/', | |
'*://*.twitter.com/', | |
'*://*.youtube.com/', | |
'*://*.instagram.com/' | |
] | |
let active = {}; | |
const end = () => { | |
if (active.name) { | |
const timeDiff = parseInt((Date.now() - active.time) / 1000); | |
console.log(`You used ${timeDiff} seconds on ${active.name}`); | |
active = {}; | |
} | |
} | |
const getActiveTab = () => { | |
return new Promise(resolve => { | |
chrome.tabs.query({ | |
active: true, | |
currentWindow: true | |
}, activeTab => { | |
resolve(activeTab[0]); | |
}); | |
}); | |
} | |
const setActive = async () => { | |
const activeTab = await getActiveTab(); | |
if (activeTab) { | |
const { url } = activeTab; | |
// check if the tab's url is among the arrays of url | |
let host = new URL(url).hostname; | |
host = host.replace('www.', '').replace('.com', ''); | |
if (urls.some(each => each.includes(host))) { | |
// set the site and current time | |
if (active.name !== host) { | |
// if a different site is active then end the existing site's session | |
end(); | |
active = { | |
name: host, | |
time: Date.now() | |
}; | |
console.log(`${active.name} visited at ${active.time}`); | |
} | |
} | |
} | |
} | |
chrome.tabs.onUpdated.addListener(() => { | |
setActive(); | |
}); | |
chrome.tabs.onActivated.addListener(() => { | |
if (active.name) { | |
end(); | |
} | |
// check to see if the active tab is among the sites being tracked | |
setActive(); | |
}); | |
chrome.windows.onFocusChanged.addListener(window => { | |
if (window === -1) { | |
// browser lost focus | |
end(); | |
} else { | |
setActive(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment