I'm having some issues understanding the syntax of how chrome.runtime.sendmessage sends data from my Content.js file to my chrome.runtime.onMessage Background.js file. I'm trying to inject a script to look at webpage metrics and display them in a Chrome extension popup when navigating to a new page. I'm unable to see the variables sent from my content.js script to my background.js script. I don't have any need to cache data between sessions, and only want my script running in the current tab that the user is on.
My Content.js script should be executing with the "run_at": "document_idle" located in the Manifest.js.
Content.js Runs > setBadgeAction shows metric on icon in Background.js > user can open report in extension Popup
Background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse){
chrome.browserAction.setBadgeText({
text: request.apple,
tabId: sender.tab.id
});
chrome.browserAction.setPopup({
tabId: sender.tab.id,
popup: "popup.html"
});
});
content.js:
function webFunction(){
var apple = 0;
var orange = 3;
var kiwi = 5;
var banana = 13;
chrome.runtime.sendMessage({
apple: apple,
orange: orange,
kiwi: kiwi,
banana: banana,
});
}
popup.js
chrome.tabs.query({
active: true,
currentWindow: true
});
chrome.runtime.onMessage.addListener((request,sender) =>{
document.getElementById("appleTag").innerHTML = request.apple;
document.getElementById("orangeTag").innerHTML = request.orange;
document.getElementById("kiwiTag").innerHTML = request.kiwi;
document.getElementById("bananaTag").innerHTML = request.banana;
});
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="popup.css">
<script src="popup.js"></script>
</head>
<body>
<p id ="appleTag">Apple Score</p>
<p id ="orangeTag">Orange Score</p>
<p id ="kiwiTag">Kiwi Score</p>
<p id ="bananaTag">Banana Score</p>
</body>
</html>
manifest.js
{
"name": "",
"description": "",
"version": "1.0",
"manifest_version": 3,
"action":{
"default_popup": "popup.html",
"default_icon": {
"16": "/images/16.png",
"32": "/images/32.png",
"48": "/images/48.png",
"128": "/images/128.png"
}
},
"content_scripts": [
{
"matches": [
"*://*/*"
],
"run_at": "document_idle",
"js": [
"content.js"
]
}
],
"options_page": "popup.html",
"background": {
"service_worker": "background.js"
},
// Permissions for the Extension.
"permissions": [
"storage",
"activeTab"
],
"icons": {
"16": "/images/16.png",
"32": "/images/32.png",
"48": "/images/48.png",
"128": "/images/128.png"
}
}