I need help understanding what the syntax would be to best send data from each individual tab from my Content.js, to each tab's individual report in the Pop.js. I'm very new to development.
I'm specifically trying to run these scripts once the page has stopped loading, and have a popup report for each tab showing that page's specific metrics. The data can be deleted from the cache on window close.
Content.js Runs when user navigates to page > cached in Background.js > user can open report in Popup.js by tab.id and retrieve from Cache
Background.js:
chrome.runtime.onMessage.addListener((request, sender) => {
chrome.storage.local.get('counts')
.then(data => {
if (!data.counts) data.counts = {};
data.counts['tab' + sender.tab.id] = request.counts;
chrome.storage.local.set(data)
.then(() => {
chrome.action.setBadgeText({
text: request.total.toString(),
tabId: sender.tab.id
});
});
});
});
// Clear Cache
chrome.tabs.onRemoved.addListener(tabId => {
chrome.storage.local.get('counts')
.then(data => {
if (data.counts) delete data.counts['tab' + tabId];
chrome.storage.local.set(data);
});
});
content.js:
if (document.readyState === 'complete') {
pageFunction();
} else {
window.addEventListener('load', pageFunction);
}
function pageFunction(){
var images = document.getElementsByTagName("img").length;
var iFrames = document.getElementsByTagName("iframe").length;
var total = images + iFrames;
var counts = {images, iFrames, total};
chrome.storage.local.set(counts); // persist data
chrome.runtime.sendMessage(counts); // send to background
}
popup.js
chrome.tabs.query({
active: true,
currentWindow: true
})
.then(tabs => {
var tab = tabs[0];
chrome.storage.local.get('counts')
.then(data => {
var x = data.counts[tab.id];
document.getElementById("iFrameHTML").innerHTML = x.iFrames;
document.getElementById("iFrameHTML").innerHTML = x.images;
document.getElementById("iFrameHTML").innerHTML = x.total;
});
});
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="Chart.js" type="text/javascript"></script>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<p id ="totalHTML">Total Score</p>
<p id ="imgHTML">Image Score</p>
<p id ="iFrameHTML">iFrame Score</p>
<script src="popup.js"></script>
</body>
</html>
manifest.json
{
"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": [
"*://*/*"
],
"js": [
"content.js"
]
}
],
"options_page": "popup.html",
"background": {
"service_worker": "background.js"
},
"permissions": [
"storage",
"activeTab"
],
"icons": {
"16": "/images/16.png",
"32": "/images/32.png",
"48": "/images/48.png",
"128": "/images/128.png"
}
}