Reputation: 193
I'm trying to create a simple chrome extension that will read some data off the page, set a badge count on the extension icon and then display the data on my popup. However I'm struggling to get the data from my content script to my background js.
I have looked at many questions on SO about this and it seems to me like I'm doing everything right, but its still not working.
This is what I've done:
manifest.json
{
"name": "__MSG_appName__",
"version": "0.0.1",
"manifest_version": 2,
"description": "__MSG_appDescription__",
"icons": {
"16": "images/icon-16.png",
"128": "images/icon-128.png"
},
"default_locale": "en",
"background": {
"scripts": [
"scripts.babel/chromereload.js",
"scripts.babel/background.js"
]
},
"content_scripts" : [
{
"matches": ["http://localhost:9000/*"],
"js":["scripts.babel/myscript.js"]
}
],
"permissions": [],
"browser_action": {
"default_icon": {
"19": "images/icon-19.png",
"38": "images/icon-38.png"
},
"default_title": "MiAssist",
"default_popup": "popup.html"
}
}
The content script:
myscript.js
"use strict";
var names = findNames();
sendNames(names);
function findNames()
{
var names = [];
//finds names..
return names;
}
function sendNames(names)
{
// Bind event:
chrome.runtime.sendMessage(null, names, null,
function(response) {
// Do something
;
});
}
background.js
'use strict';
chrome.runtime.onInstalled.addListener(details => {
console.log('previousVersion', details.previousVersion);
});
// Bind event:
chrome.runtime.onMessage.addListener(
function(names, sender, sendResponse) {
console.log("background.js");
if(names.length > 0)
{
chrome.browserAction.setBadgeText({text: names.length});
}
});
All of this doesn't work. The onMessage anonymous function is never reached.
Could somebody please help me with this? Any help would be greatly appreciated. Thank you.
Upvotes: 2
Views: 875
Reputation: 3302
Avoid using null
for optional arguments. If you need a message and callback only - just pass only two this args.
I tried you code with my remark and it works:
chrome.runtime.sendMessage(names,
function(response) {
console.log(response);
}
);
Upvotes: 1