Is there a way to make my Chrome extension pause automatically when I switch to a different tab?

After completing the tutorial on Chrome extensions from the Google Developer Chrome site, I decided to make my own extension. My idea is to create an extension that allows users to click on any sentence within a paragraph on a webpage and highlight it by simply clicking the browser action icon. However, I encountered an issue - once activated, the highlighting feature does not stop when switching tabs or navigating to another website. How can I solve this problem?

Below is the content of my manifest.json file:

{
        "name": "Page Highlighter",
        "description": "Make the current page red",
        "version": "2.0",
        "permissions": [
            "activeTab"
        ],
        "content_scripts": [
            {
                "matches": ["http://*/*"],
                "css": ["style.css"],
                "js": ["jquery-1.11.1.min.js", "myscript.js"]
            }
         ],
        "browser_action": {
             "default_title": "highlight sentence on click"
         },
        "manifest_version": 2
    }
    

In order to achieve the desired functionality, I included a jQuery file for using jQuery and created my own myscript.js file as shown below:


$(document).ready(function()
{
    $('p').each(function() {
        $(this).html($(this).text().split(/([\.\?!])(?= )/).map(
            function(v){return '<span class=sentence>'+v+'</span>'}
         ));
     });

    $('.sentence').click(function(){
        $(this).toggleClass("highlight")
     });
});

The script above searches for text within paragraphs, splits them into sentences, and wraps each sentence in a span with the class "sentence" so that users can click on individual sentences to toggle the CSS class. The styling for highlighting the sentence in yellow is defined in the styles.css file as follows:

.highlight{
        background: yellow;
    }
    

Currently, clicking the browser action activates the extension and enables sentence highlighting. However, I am seeking a solution to ensure that the highlighting feature stops when switching tabs or navigating to a new website. How can I implement this functionality?

Answer №1

Understanding the Issue

It appears that there may be some confusion regarding the functionality of a browser action. To control your extension using a browser action, you will need to set up a listener for the onClick event of the browserAction. This allows you to inject scripts and CSS into the current page when the user clicks on the browser action.

Solution Approach

To address this issue, start by making edits to your manifest.json. You can remove the "content_scripts" field as it's not necessary for injecting scripts on click. Instead, add the "background" field for your background.js script and grant permission for the tabs API. Your updated manifest.json should look like this:

{
  "name": "Page highlight ",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab",
    "tabs"
   ],
   "background" {
       "scripts": ["background.js"]
   },
   "browser_action": {
    "default_title": "highlight sentence on click"
  },
  "manifest_version": 2
}

Next, update your myscript.js by removing the $(document).ready(...) listener and correcting the code that uses the .map() method. Ensure to include your script without relying on the document ready state since it may have already loaded. Here is how your modified myscript.js should look:

$('p').each(function() {
    $(this).html($(this).text().split(/([\.\?!])(?= )/).map(
        function(v){return '<span class="sentence">'+v+'</span>'}
    ).join(''));
});

$('.sentence').click(function(){
    $(this).toggleClass("highlight");
});

In your background.js, remember to add a listener to the chrome.browserAction.onClick event and inject the required scripts and CSS using chrome.tabs.executeScript() and chrome.tabs.insertCSS() upon clicking the browser action.

Please note: For extensions developed after January 2021, consider adopting Manifest V3 along with chrome.scripting.executeScript() and chrome.scripting.insertCSS() (with scripting permission) instead of chrome.tabs.executeScript().

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.1.min.js"});
    chrome.tabs.executeScript(tab.id, {file: "myscript.js"});
    chrome.tabs.insertCSS(tab.id, {file: "style.css"});
});

Following these steps will enable you to inject the script into the page upon clicking the extension's browser action, allowing you to highlight sentences as intended.

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

Implementing a personalized pipe to enhance search functionality in a data table

I am currently working on a project that involves displaying data in a table. I want to add a search bar functionality that allows users to filter the table data. I have attempted to use a pipe to achieve this, but I am facing challenges and unsure of the ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

When dynamically loaded HTML is involved, Javascript ajax calls often fail to execute properly

Currently, I am in the process of creating a JavaScript script that can facilitate clicking through <a href> links by only replacing the inner HTML instead of reloading the entire page. The interesting thing is, it seems to be functioning properly, e ...

Firebase Error: The property 'ac' is not defined and cannot be read

When authenticating on my web app, I utilize this straightforward code: firebase.auth().signInWithCustomToken(token).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); Howev ...

Exploring the contrast between using '-save' and '--save' when executing the 'npm install' command

After working with Node.js for half a year, I'm still puzzled about the distinction between npm install pkg -save and npm install pkg --save. Can someone please clarify the difference for me? ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

Guide to implementing onhashchange with dynamic elements

Hey there! I've encountered a problem with two select boxes on my webpage, each in different anchors (one on the page, the other in an iframe). What I'm trying to achieve is for the code to recognize which anchor it's in and then pass the se ...

What is the best way to achieve a sleek and seamless scrolling effect on a webpage?

Is there a way to improve the scrolling effect on my website using jQuery? I find that the default scrolling behavior in most browsers is jumpy and I'm hoping to achieve a more smooth and polished look. ...

I'm trying to use Javascript to dynamically remove rows, but my code seems to be causing some issues

When a user enters text into a form, it is stored in a variable called 'userInput'. I have an HTML table with the ID "myTable". My goal is to use JavaScript to iterate through the table and remove all rows where the value of the 3rd column does n ...

Tips on sending the total value of a form to a PHP script

Looking for help with a PHP script to calculate the sum of checked checkboxes with corresponding numeric values. For example, if checkbox 1 = 80; checkbox 2 = 21; and checkbox 3 = 15, and the user checks checkboxes 2 and 3, the PHP should output 36. I hav ...

Trouble with linkage in jQuery for AJAX requests in an external .js document

My asp.net application has a master file that includes the jquery.js file. On another page that uses this master page, I have my own jquery code. I attempted to move this code to an external file and then include it in my .aspx file. While most functions ...

Tips for handling timeouts when a connection fails to establish

Is there a default timeout value in the socket.io API that triggers after multiple connection attempts fail? In my application, I am trying to connect to a Node.js server using socket.io. If the connection is not established or unreachable, I want to recei ...

Changing a single variable into an array that holds the variable in JavaScript

Is there a way to change 5 into [5] using JavaScript? I need this functionality for a method that utilizes jQuery's $.inArray. It should be able to handle both scalar variables and arrays, converting scalars into arrays with a single element. ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Live graph updating with x-axis scrolling in Chart.js version 4

I have a graph created with Chart.js that updates every 500ms by checking for new data from the backend. When new data is found, it is added to the graph. setInterval(function(){ let num = pick_numb() num.then(function(result) { addData(my ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

The `indexOf` method is incorrectly returning -1 despite the value being found within the array

I am facing an issue with the indexOf function in my code. I have a collection called placeCollection which contains an array named locFrnd. Since I couldn't use the indexOf function directly on the locFrnd array of objects, I created a new array call ...

What is the best way to initiate a JavaScript AJAX call within a PHP function?

My PHP if statement currently just reloads the page: header('Location: index.php'); Check out the site here Instead, I am looking to use a basic AJAX request in JavaScript to load a page called register-success.php into the div: function load ...

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...