I am creating a simple chrome extension that does something on load. I read that it can be more efficient and better overall to use chrome.webNavigation.onCompleted instead of chrome.tabs.onUpdated. I am not sure exactly why, but I am also using a filter because I only need this extension to work on a specific place. But when I try to use the webNavigation object, it doesn't work. Here's my code:
background.js using onUpdated (works)
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
"message": "site_loaded"
}, function(response) {});
});
}
});
background.js using webNavigation (doesn't work)
const filter = {
url: [
{
urlMatches: 'https://example.com/*',
},
],
};
chrome.webNavigation.onCompleted.addListener((d) => {
console.log("going to send message now");
chrome.tabs.sendMessage( 0 , {
"message": "site_loaded"
}, function(response) {
console.log("response hello",response)}
);
}, filter);
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("message site loaded received", request.message);
if( request.message === "site_loaded" ) {
//code
}
sendResponse(true);
return true;
});
manifest:
{
"name": "nn",
"description": "desc",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": [
"tabs",
"webNavigation"
],
"icons": {
....
},
"content_scripts": [
{
"matches": [
"https://example.com/*"
],
"js": ["content.js"]
}
]
}
I guess I do have something that works, but I wanted to understand why that doesn't work and I could figure it out from the documentation.
Edit: I actually also noticed that on the case where I said it works, when I navigate the site I am getting errors from the background.js:
Unchecked runtime.lastError: The message port closed before a response was received.
which I thought was fixed by doing
sendResponse(true);
return true;
on the content.js, but they were not.. So I don't know how to get it to work correctly at all I guess. And the docs are not helping.