Search code examples
javascriptfunctioneventsgoogle-chrome-extension

Function won't run when context item menu is clicked on (Chrome Web Extension)


I am developing a Chrome extension that is supposed to block websites if it finds a URL match in an array, and I am very very new to using JS. I am trying to add a context menu item that will quickly add an item to the array. I'm not able to get the code inside of the function to execute. To add to my confusion, I copy and pasted another person's code for a different use, and that one worked just fine. I am not sure what mistake I am making here. Nothing from other posts I have seen has worked for me.

// setup context menu item
    chrome.contextMenus.create({
        "id": "addSite",
    "title": "Task Tracker",
    "contexts": ["all"]
}); 

// when any menu item is interacted with
chrome.contextMenus.onClicked.addListener(
    function addToArray() {
        alert("its working")
    }
);

I am expecting it to send a debugging alert when the context menu item is selected.

This is the other code that I tried, and it worked just fine, but when I modified it to only send the alert, it did not work.

chrome.contextMenus.onClicked.addListener(function(info, tab){
    //the URL that will be added to based on the selection
    baseURL = "http://en.wikipedia.org/wiki/";
    var newURL = baseURL + info.selectionText;
    //create the new URL in the user's browser
    chrome.tabs.create({ url: newURL });

Solution

  • Service workers don't have a DOM, so they can't call alert.
    The following error is output to DevTools of Service Worker.

    Error in event handler: ReferenceError: alert is not defined