'Can not use variables from background-script inside the popup-script after using getBackgroundpage()

I am new to chrome extensions. I want to program a timer that alerts the user every 40 minutes and tells him to drink a cup of water, but I ran in some issues.

After some googling I learned that I have to use the background-script to calculate the time and somehow pass it to the popup-script(because as soon as the popup is closed, the JS-session is closed too).

I am trying to solve this with getBackgroundPage(). With the code, shown below I get this error: **Uncaught TypeError: Error in invocation of runtime.getBackgroundPage(function callback): No matching signature. at popup.js:6**

This is my code:

HTML:

//background.js

setInterval(updateTimer, 1000);

function updateTimer() {
  const StartingMinutes = 40;
  let timeinSec = StartingMinutes * 60;
  const minutes = Math.floor(timeinSec / 60);
  let seconds = timeinSec % 60;

  seconds = seconds < 10 ? '0' + seconds : seconds;

  timeinSec--;

  timeinSec = timeinSec < 0 ? 0 : timeinSec;

  return minutes, seconds;
}

//popup.js

setInterval(function() {
  let BGPage = chrome.runtime.getBackgroundPage();
  let BGPage_Time_Data = BGPage.updateTimer();
  console.log(BGPage_Time_Data)
}, 1000)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="popup.css">
  <title>Hydration Timer</title>
</head>

<body>
  <div>
    <h3>You should drink a cup of water in:</h3>
  </div>
  <div class="drink-timer"><span class="minutes-span">40</span> : <span class="seconds-span">00</span></div>
  <script src="popup.js"></script>
</body>

</html>

manifest.json:


    {
        "name": "Hydro Homies",
        "description": "Do not forget to drink my Homies",
        "version": "1.0",
        "manifest_version": 3,
        "background": {
          "service_worker": "background.js"
        },
        "permissions": ["background"], 
        "action": {
          "default_popup": "popup.html"
        }
      }

Could you please help me understand, how I can access the minutes and seconds variables in the popup-script and how to handle the error.

Thanks :)



Solution 1:[1]

Background pages are replaced by service workers in Manifest V3

Checkout the Manifest V3 migration checklist: https://developer.chrome.com/docs/extensions/mv3/mv3-migration-checklist/

Moving from timers to alarms: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/#alarms

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raja