I made my first browser extension. The first version works decently, but can be improved, so I'm refactoring.... And in this new version, I'm using a page_action
because it's important that this extension only works on one url pattern: *://*.website.com/abc*
. The popup shows up fine on only this page, and won't show on others - exactly as I want it, but I can't get the popup.js
to send a message to my background.js
so it runs a programmatic injection on the DOM of the current browser url via content_script.js
.
For some reason, it also shows the icon as colored on every page (which I want grey), and I was under the impression that the ShowPageAction()
method could auto grey out anything that didn't meet the conditions for it. Here's my code for it all.
manifest.js
{
"name": ".........",
"description" : "...........",
"version": "1.0",
"manifest_version": 2,
"icons": {
"16": "images/a.png",
"32": "images/b.png",
"48": "images/c.png",
"128": "images/d.png"
},
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/a.png",
"32": "images/b.png",
"48": "images/c.png",
"128": "images/d.png"
}
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": ["tabs", "activeTab", "declarativeContent", "storage", "webNavigation", "*://*.website.com/abc*"],
}
background.js
The 2nd listener below isn't receiving the message.
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.local.set({some_val: 0});
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher(
{pageUrl: {urlContains: '.website.com/abc'},}
)],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.some_msg == 'some_msg'){
chrome.tabs.executeScript(null, {file: 'content_script.js'});
}
});
popup.js
For the following, I've tried both chrome.tabs.sendMessage()
, and chrome.runtime.sendMessage()
, but neither are working... my_function
is also bound to an event handler on the popup, and works fine, it's just doesn't sendMessage()
.
function my_function(){
....
// chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// chrome.tabs.sendMessage(tabs[0].id, {some_msg : 'some_msg'})
// })
chrome.runtime.sendMessage({some_msg : 'some_msg'});
....
};
content_script.js
var e = document.getElementById('abcde');
// do stuff with the browser DOM ---- NOT the popup DOM.
What am I doing wrong?