Guest User

Untitled

a guest
Nov 20th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. const urls = [
  2. '*://*.facebook.com/',
  3. '*://*.twitter.com/',
  4. '*://*.youtube.com/',
  5. '*://*.instagram.com/'
  6. ]
  7.  
  8. const STORAGE = chrome.storage.local;
  9.  
  10. let active = {};
  11.  
  12. const update = async (host, seconds) => {
  13. const currentDate = new Date().toISOString().substr(0, 10);
  14. // get the data saved for the current date
  15. const data = await getData(currentDate);
  16. if (data[host]) {
  17. data[host] += seconds;
  18. } else {
  19. data[host] = seconds;
  20. }
  21. // save the updated value
  22. save(currentDate, data);
  23. }
  24.  
  25. const save = (key, value) => {
  26. return new Promise((resolve) => {
  27. STORAGE.set({ [key]: value }, () => {
  28. resolve();
  29. });
  30. });
  31. }
  32.  
  33. const getData = (key) => {
  34. return new Promise((resolve) => {
  35. STORAGE.get(key, result => (result[key] ? resolve(result[key]) : resolve({})));
  36. });
  37. }
  38.  
  39. const end = () => {
  40. if (active.name) {
  41. const timeDiff = parseInt((Date.now() - active.time) / 1000);
  42. console.log(`You used ${timeDiff} seconds on ${active.name}`);
  43. // add it to the number of seconds already saved in chrome.storage.local
  44. update(active.name, timeDiff);
  45. active = {};
  46. }
  47. }
  48.  
  49. const getActiveTab = () => {
  50. return new Promise(resolve => {
  51. chrome.tabs.query({
  52. active: true,
  53. currentWindow: true
  54. }, activeTab => {
  55. resolve(activeTab[0]);
  56. });
  57. });
  58. }
  59.  
  60. const setActive = async () => {
  61. const activeTab = await getActiveTab();
  62. if (activeTab) {
  63. const { url } = activeTab;
  64. // check if the tab's url is among the arrays of url
  65. let host = new URL(url).hostname;
  66. host = host.replace('www.', '').replace('.com', '');
  67. if (urls.some(each => each.includes(host))) {
  68. // set the site and current time
  69. if (active.name !== host) {
  70. // if a different site is active then end the existing site's session
  71. end();
  72. active = {
  73. name: host,
  74. time: Date.now()
  75. };
  76. console.log(`${active.name} visited at ${active.time}`);
  77. }
  78. }
  79. }
  80. }
  81.  
  82. chrome.tabs.onUpdated.addListener(() => {
  83. setActive();
  84. });
  85.  
  86. chrome.tabs.onActivated.addListener(() => {
  87. if (active.name) {
  88. end();
  89. }
  90. // check to see if the active tab is among the sites being tracked
  91. setActive();
  92. });
  93.  
  94. chrome.windows.onFocusChanged.addListener(window => {
  95. if (window === -1) {
  96. // browser lost focus
  97. end();
  98. } else {
  99. setActive();
  100. }
  101. });
Add Comment
Please, Sign In to add comment