0

I've created a Chrome extension with a countdown timer on the popup, everything works well, but anytime I close or refresh the thing the timer continues from where it left off, I want it to be counting down even when the extension is closed. How would I do this?

Code

const lifetime = document.getElementById('premium-btn');
const countdown = document.getElementById('countdown');
let timeSecond = 345600;

// Button
lifetime.addEventListener('click', function() {
    window.open("https://flutterwave.com/pay/fonsnatcher-lifetime", "_blank");
});

//
chrome.storage.sync.get(['seconds'], function(result) {
    if(typeof result.seconds !== "undefined") {
        timeSecond = result.seconds;
    }
  }); 
  //

const timer = setInterval(() => {
    timeSecond--;
    displayTime(timeSecond);


    if(timeSecond == 0 || timeSecond < 1){
        clearInterval(timer);
        countdown.innerHTML = "Completed";
    }

    chrome.storage.sync.set({seconds: timeSecond});
}, 1000)

function displayTime(second) {
    const days = Math.floor(second / 24 / 60 / 60);
    const hoursLeft = Math.floor((second) - (days * 86400));
    const hours = Math.floor(hoursLeft / 3600);
    const minsLeft = Math.floor((hoursLeft) - (hours * 3600));
    const min = Math.floor(minsLeft / 60);
    const sec = Math.floor(second % 60);

    countdown.innerHTML = `${ days < 10 ? '0' : '' }${ days }:${ hours < 10 ? '0' : '' }${ hours }:${ min < 10 ? '0' : '' }${ min }:${ sec < 10 ? '0' : '' }${ sec }`;
    
}

function onTimeEnd() {

}
Hitman DD
  • 47
  • 1
  • 11
  • Do it in the background script. See also [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Nov 25 '21 at 07:25
  • Ok, which part should I put in the background script? and how exactly would I connect the two scripts after? – Hitman DD Nov 25 '21 at 14:55

0 Answers0