Reputation: 5590
Does chrome have an api to disable (and thus gray out) chrome extensions on certain urls or do I just have to have a if statement that checks the url and switches out the icon accordingly?
Upvotes: 5
Views: 3405
Reputation: 4300
You use browserAction instead of browserAction, but there are some things to note:
According to my test, you cannot use "<all_urls>" and "activeTab" in "content_scripts" and "Permissions", otherwise the icon will always be colored.
"content_scripts": [
{
"matches": ["<all_urls>"], // error
"js": ["content.js"],
}
],
"permissions": ["<all_urls>", "activeTab", "storage", "tabs", "declarativeContent"], // error
narrow down
"content_scripts": [
{
"matches": ["http://127.0.0.1/*"],
"js": ["content.js"],
}
],
"permissions": ["storage", "tabs", "declarativeContent"],
background.js
let rule1 = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: '127.0.0.1' },
}),
],
actions: [new chrome.declarativeContent.ShowPageAction()],
};
chrome.declarativeContent.onPageChanged.removeRules(undefined, data => {
chrome.declarativeContent.onPageChanged.addRules([rule1], data => {
console.log('addRules', data);
});
});
The removeRules operation is performed because the rule will be added repeatedly every time the extension is refreshed.
Reference question link
https://stackoverflow.com/a/63434774/9854149
Upvotes: 1
Reputation: 49150
add to manifest.js:
"background": { "scripts": ["background.js"] },
"content_scripts" :[
{
"matches" : [
"*://*.example.com/*"
],
"js" : ["main.js"],
"run_at" : "document_idle"
}
]
main.js:
chrome.runtime.sendMessage({type:'showPageAction'});
background.js:
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.type === 'showPageAction'){
chrome.pageAction.show(sender.tab.id);
}
});
Upvotes: 1
Reputation: 10897
You could use chrome.declarativeContent
, it allows you to show page action depending on the URL of a web page and the CSS selectors its content matches.
You could create conditions ( yes, you could use regex) and actions ( ShowPageAction
SetIcon
) via a constructor like new chrome.declarativeContent.PageStateMatcher
and new chrome.declarativeContent.ShowPageAction()
. Detailed sample are listed in the api documentation.
var rule2 = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: 'www.google.com', schemes: ['https'] },
css: ["input[type='password']"]
}),
new chrome.declarativeContent.PageStateMatcher({
css: ["video"]
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
chrome.runtime.onInstalled.addListener(function(details) {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([rule2]);
});
});
Upvotes: 1