Executing a background.js function in response to an event trigger within the active tab in a Chrome extension

I am facing an issue where I am getting an error saying "resetTime is not defined" when running the code below. I have tried passing the function as an argument, but that did not solve the problem. Do I need to come up with a new logic to reset the time inside the "chrome.scripting.executeScript" method?

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],
    });
  });
});

Answer №1

Your current code may not be functioning as intended, as the value of time remains constant at 0. To establish communication between a content script and a background service worker, refer to the methods outlined here.

Furthermore, following the transition to manifest version 3, it is advised against using setInterval within the background service worker. Instead, utilize the chrome.alarms API.

To illustrate how you can set an alarm from a content script, consider the following example:

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();
        });
      },
    });
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that clicking on various links will result in them opening in a new pop-up window consistently

I am facing an issue with my HTML page where I have Four Links that are supposed to open in separate new windows, each displaying unique content. For instance: Link1 should open in Window 1, Link2 in Window 2, and so on... The problem I'm encounter ...

The Material-ui DatePicker seems to be malfunctioning and as a result, the entire form is not

Struggling to get my DateTimePicker component (could be DatePicker) working after following installation instructions from various sources. I've spent a day and a half attempting to make it functional without success. If you can help me create a separ ...

Scripts in iframes within webviews are not preloading and executing properly

When using the <webview> tag in the renderer process within the <body> of a web page, the following code is used: <webview src="http://somewebpage.com" preload="somescript.js"> The script somescript.js will be execute ...

Can an event be passed from one Vue.js component to another without relying on a global EventBus?

I have two independent components that are not directly related to each other. However, I want them to be able to communicate so that when an event is triggered in one component, the other component can respond accordingly. For example, let's conside ...

"Master the art of creating a curved circular arrow using a combination of HTML, SVG, D3.js

I am looking to design an SVG circle with a fading stroke that blends into the background and features an arrow at one end. The goal is for the ring to fade out completely right above the arrow, similar to the visual reference provided in the image.view ex ...

Error message encountered in React Material-UI while attempting to run the basic Hello World test - Invalid hook call

My plan is to kick off a project using React and Material-UI. I decided to start with the simplest Hello World example based on the official documentation, in a brand new Ubuntu OS. However, when I tried running the code, an error popped up! Here's wh ...

Trigger Bootstrap Modal using ASP Razor code within MVC Model value execution

I have a web application built with ASP .NET Core and MVC. The app features a side menu that allows the user to navigate through different pages based on their workflow. For example, when a user logs in for the first time, they are directed to the Home pag ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Tips for achieving a gradual transformation of an element according to the scrolling position

I have been experimenting with using waypoints for two specific purposes. The first objective is to determine whether a user is scrolling up or down and if the container comes into view. However, this functionality is not working as expected. The sec ...

AngularJS: Enhancing Date Display and Organization

Looking to change the date format from "Mon Oct 12 2015 00:00:00 GMT+0530 (IST)" to "YYYY/MM/DD" within my controller. ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

What is the procedure for deactivating a plugin within the replace feature of CkEditor?

Is there a way to disable image-upload on specific CKEditor textareas without affecting all of them through the config.js file? I'm wondering if it's possible to achieve this using the .replace method. For example: CKEDITOR.replace("meTextarea" ...

Customize hoverIntent to support touch events on mobile devices

Hello everyone. I've encountered an issue with hoverintent.js, a jQuery plugin that handles mouseOver events differently than usual. I am facing constraints where I can only modify the JavaScript of this plugin, but I need it to be compatible with to ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Connecting UserIDs with Embedded Documents in Mongoose

My goal is to connect individuals with each other by embedding a Match document in the user's matches array. This is my User Model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Match = new Schema({ with: ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...