Time Spent on Youtube

A simple timer that shows how much time you spent on Youtube today.

  1. // ==UserScript==
  2. // @name Time Spent on Youtube
  3. // @version 2022.08.30.07.46
  4. // @description A simple timer that shows how much time you spent on Youtube today.
  5. // @license MIT
  6. // @author Marco Dalla Gatta
  7. // @namespace https://github.com/marcodallagatta/userscripts/raw/main/youtube-time-spent/
  8. // @match https://www.youtube.com/*
  9. // @icon https://icons.duckduckgo.com/ip2/youtube.com.ico
  10. // ==/UserScript==
  11.  
  12. (function () {
  13. "use strict";
  14.  
  15. const background = false; // 'true' also counts when YT is in a background tab, 'false' only counts active tab
  16. const showInTitle = true; // 'true' prepend the minutes before the title in the tab
  17. const originalTitle = document.title;
  18. const resetTime = 4; // time when the timer resets, 24h time (0 = midnight, 4 = 4AM, 15 = 3PM)
  19.  
  20. const today = new Date();
  21. const dd = String(today.getDate()).padStart(2, "0");
  22. const mm = String(today.getMonth() + 1).padStart(2, "0");
  23. const yyyy = today.getFullYear();
  24. const todayYYMMDD = yyyy + mm + dd;
  25. const hours = today.getHours();
  26.  
  27. let spent = 0;
  28. if (localStorage.getItem("date") !== todayYYMMDD && hours >= resetTime) {
  29. localStorage.setItem("date", todayYYMMDD);
  30. localStorage.setItem("spent", 0);
  31. } else {
  32. spent = parseFloat(localStorage.getItem("spent"));
  33. }
  34.  
  35. const inDOM = document.getElementById("start");
  36. let elem = document.createElement("span");
  37. elem.style = "color:white;font-size:2rem";
  38. inDOM.appendChild(elem);
  39. function showAlert(time) {
  40. const mm = (Math.trunc(time) % 60).toString();
  41. if (time > 60) {
  42. const hh = Math.trunc(time / 60).toString();
  43. elem.innerText = `${hh}h ${mm}m`;
  44. if (showInTitle) document.title = `${hh}h${mm.padStart(2, "0")}m ${originalTitle}`;
  45. } else {
  46. elem.innerText = `${mm}m`;
  47. if (showInTitle) document.title = `${mm.padStart(2, "0")}m ${originalTitle}`;
  48. }
  49. }
  50.  
  51. setInterval(function () {
  52. if (background || document.hasFocus()) {
  53. spent = parseFloat(localStorage.getItem("spent")) + 0.25;
  54. localStorage.setItem("spent", spent);
  55. showAlert(spent);
  56. }
  57. }, 15000); // 15s
  58.  
  59. // triggers after a few seconds since by default YT overwrites titlebar after a while on load \_(ツ)_/
  60. setTimeout(function () { showAlert(spent) }, 2000);
  61.  
  62. })();