Reputation: 4541
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?
Upvotes: 11
Views: 3713
Reputation: 1735
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'
}
Upvotes: 1