babaysteps
babaysteps

Reputation: 393

How can I get my Chrome extension to stop when i move to another tab?

I've done the tutorial on Chrome extension on the google developer chrome site and am trying to create my own. Basically I want to make an extension that, when the browser action is clicked, makes you able to click on any sentence of a paragraph on a page and highlight it. When you move to another tab, you have to click it again to activate it. The problem is that, unfortunately it doesn't seem to stop when I move to another tab or navigate to another site. How can I make it stop?

Here is my manifest.json file:

{
  "name": "Page highlight ",
  "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
}

I added a jQuery file to use jQuery, and my myscript.js file, which looks like this:

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

It basically looks for the text in any paragraph then cuts it into sentences and puts them in a span with class="sentence", so I can click any sentence and toggle the CSS class, which stile is defined in my styles.css file where I just highlights the sentence in yellow, here it is:

.highlight{
    background: yellow;
}

Now, when I click the browser action (extension icon) it activates and I can click a sentence to highlight it, but I want it to stop when I go to another tab or navigate to another site. How can I accomplish this?

Upvotes: 1

Views: 460

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69276

Issue

It looks like you didn't understand the behavior of a browser action. If you want to control your extension using a browser action you will need to add a listener to the onClick event of the browserAction, so when the user clicks it you can inject the scripts and the CSSs inside the current page.

Solution

First of all, edit your manifest.json, you don't need the "content_scripts" field, because you will only need inject your script when the user clicks. So add the "background" field for your background.js script and the permission for the tabs API. Here is what your manifest.json will look like after this changes:

{
  "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
}

Before editing background.js, you'll have to remove the $(document).ready(...) listener, because if you insert your script into a page clicking the browser action, it is most likely inserted into a page that has already loaded, so the ready listener will not work. Also, your code is wrong, because the .map() method returns an array, so you have to .join() it before replacing the html of the element. I edited it for you. Your new myscript.js will be this:

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

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

Ok, now in your background.js you need to add a listener to the chrome.browserAction.onClick event and inject the scripts and the CSSs you need using chrome.tabs.executeScript() and chrome.tabs.insertCSS() when the user clicks the browser action.

NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() and chrome.scripting.insertCSS() (with the 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"});
});

That's all you need, now when you click the extension's browser action the script will be injected into the page and you'll be able to highlight your sentences.

Upvotes: 1

Related Questions