Sunday, April 11, 2021

Service worker registration failed. Cannot read property 'onClicked' of undefined

Given this background.js:
// eslint-disable-next-line no-undef
chrome.action.onClicked.addListener((tab) => {
    console.log("working");

    // eslint-disable-next-line no-undef
    chrome.tabs.sendMessage(
        // tabs[0].id,
        tab.id,
        { action: "CHANGE_COLOR" },
        // eslint-disable-next-line no-unused-vars
        function (response) {}
    );

});

I'm using manifest version 3:
{
    "name": "Chinese word separator",
    "description": "Put spaces between words",
    "version": "1.0",
    "manifest_version": 3,    
    "background" : {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "css": [],
            "js": ["contentScript.js"]
        }
    ]  
}


And I received this error:

To fix the error, add the action property even if it is empty:

{
    "name": "Chinese word separator",
    "description": "Put spaces between words",
    "version": "1.0",
    "manifest_version": 3,    
    "action": {},
    "background" : {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "css": [],
            "js": ["contentScript.js"]
        }
    ]  
}
It is advisable to wrap the background.js via a wrapper so you'll get better error message, so if there's no action property in manifest.json..
{
    "name": "Chinese word separator",
    "description": "Put spaces between words",
    "version": "1.0",
    "manifest_version": 3,    
    "background" : {
        "service_worker": "background-wrapper.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "css": [],
            "js": ["contentScript.js"]
        }
    ]  
}
..and you wrap the background via wrapper (e.g., background-wrapper.js)..
try {
    // eslint-disable-next-line no-undef
    importScripts("./background.js");
} catch (e) {
    console.error(e);
}
..you will receive a more descriptive error instead:
background-wrapper.js:5 TypeError: Cannot read property 'onClicked' of undefined
    at background.js:1
    at background-wrapper.js:3
(anonymous) @ background-wrapper.js:5
To fix the error, add action on manifest.json

No comments:

Post a Comment