Search code examples
javascriptgoogle-chromegoogle-chrome-extension

how to execute a background.js function when an event is fired in the current tab (chrome extension)


when i run the following code i get resetTime is not defined , i tried passing the function as an argument bu that did not work, am i supposed to write new logic to reset the time inside "chrome.scripting.executeScript" :

let time = 0;

function resetTime() {
  time = 0;
  chrome.storage.sync.set({ time: time });
  console.log("Timer reset");
}

setInterval(() => {
  chrome.storage.sync.get(["time"], (result) => {
    console.log("Current time: " + result.time);
  });
}, 1000);

chrome.tabs.onActivated.addListener((activeInfo) => {
  chrome.tabs.get(activeInfo.tabId, (tab) => {
    chrome.scripting.executeScript({
      target: { tabId: activeInfo.tabId },
      function: (resetTime) => {
        document.addEventListener("mousemove", (e) => {
          resetTime();
        });

        document.addEventListener("mousedown", (e) => {
          resetTime();
        });
      },
      args: [resetTime],
    });
  });
});

Solution

  • Your code doesn't seem to do anything (time will always be 0). In any case, if you want to communicate with the background service worker from a content script, you'll have to use one of the methods described here.

    Also, since the change to manifest version 3, using setInterval in the background service worker is not recommended, instead of that, you should use the chrome.alarms API.

    Because your code doesn't seem to do anything, I will just add an example of how you could set an alarm from a content script.

    chrome.alarms.onAlarm.addListener(async () => {
      const values = await chrome.storage.get('time');
      const time = ++values.time;
      console.log(time);
      await chrome.storage.set({ time });
    });
    
    chrome.runtime.onMessage.addListener((sender, request, sendResponse) => {
      if (request.cmd === 'resetTimer') {
        chrome.storage.set({ time: 0 });
        chrome.alarms.create({ name: 'interval', delayInMinutes: 1, periodInMinutes: 1 });
      }
    });
    
    chrome.tabs.onActivated.addListener((activeInfo) => {
      chrome.tabs.get(activeInfo.tabId, (tab) => {
        chrome.scripting.executeScript({
          target: { tabId: activeInfo.tabId },
          function: () => {
            function resetTimer() {
               chrome.runtime.sendMessage({ cmd: 'resetTimer' });
            }
            document.addEventListener("mousemove", (e) => {
              resetTime();
            });
    
            document.addEventListener("mousedown", (e) => {
              resetTime();
            });
          },
        });
      });
    });