Search code examples
javascriptdatabasegoogle-chrome-extensiongoogle-chrome-devtoolsbackend

How to store data within a Google Chrome Extension?


I'm trying to make a google chrome extension, where there is a stopwatch where users can click start, stop or reset buttons. Upon clicking this stopwatch, I want the time to save within the extension itself so that users can always click out of the extension, but the time on the stopwatch will always keep going (until they press stop). I also want to constantly display the running time on the users screen, like this extension here: [1]: https://i.sstatic.net/k0HMg.png

Here is my code:

//defining variables.
let seconds = 0;
let minutes = 0;
let hours = 0;

//these variables work to add a second "0" when there is only 1 digit in each respective value.
let displaySeconds = 0;
let displayMinutes = 0;
let displayHours = 0;

//this variable is used to work the setInterval() method.
let interval = null;

//this variable holds the stopwatch's status.
let status = "stopped";

//stopwatch function, determining when to increment next value, and when to bring current values to zero.
function stopWatch() {

  seconds++;

  if (seconds / 60 === 1) {
    seconds = 0;
    minutes++;

    if (minutes / 60 === 1) {
      minutes = 0;
      hours++;
    }
  }

  //if any of the values within the timer are only 1 digit in length, we will add ANOTHER zero to it. 
  if (seconds < 10) {
    displaySeconds = "0" + seconds.toString();
  } else {
    displaySeconds = seconds;
  }

  if (minutes < 10) {
    displayMinutes = "0" + minutes.toString();
  } else {
    displayMinutes = minutes;
  }

  if (hours < 10) {
    displayHours = "0" + hours.toString();
  } else {
    displayHours = hours;
  }

  //this part of the function will update the display every 1 second.
  document.getElementById("stopwatch-face").innerHTML = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}

function startStop() {
  if (status === "stopped") {
    interval = window.setInterval(stopWatch, 1000); //this plays out a certain function every set amount of time
    document.getElementById("startStop").innerHTML = "Stop";
    status = "start";
  } else {
    window.clearInterval(interval);
    document.getElementById("startStop").innerHTML = "Start";
    status = "stopped";
  }
}

//this function will reset the stopwatch.
function reset() {

  window.clearInterval(interval);
  seconds = 0;
  minutes = 0;
  hours = 0;
  document.getElementById("stopwatch-face").innerHTML = "00:00:00";
  document.getElementById("startStop").innerHTML = "Start";

}
//This is what you do instead of "onclick", to make extensions....:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("startStop").addEventListener("click", startStop);
});

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("reset").addEventListener("click", reset);
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Snap Focus</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;1,300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/fontawesome.min.css" integrity="sha384-wESLQ85D6gbsF459vf1CiZ2+rr+CsxRY0RpiF1tLlQpDnAgg6rwdsUF1+Ics2bni" crossorigin="anonymous">

  <script type="text/javascript" src="popup.js"></script>

  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="body">

  <body>
    <div class="content">
      <div class="modal-header">
        <div class="header">
          <h1 className="Title"><strong>Snap Focus</strong></h1>
        </div>
        <div class="modal-subheader">
          <p><i>Just press start to block unnecessary websites, and be more productive!</i></p>
        </div>
        <hr>
      </div>
      <div id="stopwatch-face">
        00:00:00
      </div>
      <div class="buttons">
        <button id="startStop">Start</button>
        <button id="reset">Reset</button>
      </div>
      <br>
    </div>
  </body>
</div>

</html>

Any help is greatly appreciated!


Solution

  • Hi here's a small script I call to save data in an extension, hopefully you can use it. You'll probably need to add permission in your manifest, here's the chrome documentation

    // Manage access_token storage
    
    const TOKEN_NAME = 'faunaToken';
    
    export function setAuth(token) {
      chrome.storage.sync.set({ [TOKEN_NAME]: token });
    }
    
    export function removeAuth() {
      chrome.storage.sync.remove([TOKEN_NAME]);
    }
    
    export function getAuth() {
      return new Promise((resolve) => {
        chrome.storage.sync.get([TOKEN_NAME], async (token) => {
          resolve(token[TOKEN_NAME]);
        });
      });
    }
    

    and then use it like

    import { setAuth } from '../scripts/AuthToken';
    
    somePromise.then(data => setAuth(data.token));
    

    By the way you probably don't want to call this every second to update the counter. It would probably be better to on click save the timestamp to storage and have popup.js determine time since the timestamp