9

I have an extension that declaratively specifies using a content_script:

manifest.json:

"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"],
    "run_at": "document_end"
  }
],

I'm reading that by instead specifying the activeTab permission, it won't alert about permissions during installation:

https://developer.chrome.com/extensions/activeTab

My question is: how can you switch to using

"permissions":["activeTab"]

from using content_scripts?

Here's my popup.js code that calls the content_script:

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { action: "checkForCode" }, function (response) {
    if (!!response) { showResults(response.results); }
  });
});

and the content_script's event handler:

chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
    if (request.action == "checkForCode") {
        getCode(request, sender, sendResponse);//method sends callback.
        return true;
    }
});

This code works just fine, but I'm wondering how to use it with the activeTab permissions. Should I just add the content.js via chrome.tags.executeScript(), then reference it the same way?

DShultz
  • 4,381
  • 3
  • 30
  • 46
  • 5
    Your content script's declaration requests all_urls permission so activeTab won't help you unless you remove the content script declaration altogether. You can switch to programmatic injection via executeScript. There are tons of examples, see my [recent answer](https://stackoverflow.com/a/51729893) as well. And of course [the documentation](https://developer.chrome.com/extensions/content_scripts#programmatic). – wOxxOm Aug 07 '18 at 17:22

1 Answers1

1

In your manifest.json you need to set

"permissions": ["activeTab", "tabs"],

and

"background": {
    "scripts": ["content.js"],
    "persistent": false
},

your content.js as example:

// metaCode will be injected and executed in the current tab
// the returned results you can use in callbackFunction
var metaCode = 'var descr = document.querySelector("meta[name=\'description\']");' 
            + 'var keyw = document.querySelector("meta[name=\'keywords\']");' 
            + 'if (descr) var descr = descr.getAttribute("content");' 
            + 'if (keyw) var keyw = keyw.getAttribute("content");'
            + '({' 
            + '    description: descr || "",' 
            + '    keywords: keyw || "",' 
            + '})';

chrome.tabs.executeScript(
        tab.id,
        {code: metaCode}, // get meta key words
        callbackFunktion
    );

function callbackFunktion(results) {

  var result = results[0];
  var description = result.description;
  var keywords = result.keywords;
  // and so on ... whatever you want
  // to do with results from the
  // injected script from 'metaCode'

}
Hermann Schwarz
  • 1,495
  • 1
  • 15
  • 30