javascriptgoogle-chrome-extensiongoogle-chrome-devtools

Chrome extension action.onClicked


I am building a chrome extension and I use this code to open the popup in new window. (Using manifest v3) It suddenly stopped working today.

Uncaught TypeError: Cannot read properties of undefined (reading 'onClicked') Yesterday it worked just fine and it corresponds with chrome extension documentation. Anyone knows what the issue could be?

Here is my code:

chrome.action.onClicked.addListener(tab => {
    chrome.windows.create({
        url: chrome.runtime.getURL("popup.html"),
        type: "popup",
        height: 800,
        width: 516
      }, function(win) {
      });
});

Solution

  • This question was already answered, but I wanted to post a full example since I couldn't find a post that had both extension code and corresponding manifest.json.

    Here is full, valid example using Manifest V3.

    // File: manifest.json //
    
    {
        "manifest_version": 3,
        "name": "My extension",
        "description": "Extension that extends things",
        "author": "Me",
        "version": "0.1",
        "content_scripts": [
          {
            "matches": [
              "https://*"
            ],
            "js": ["content.js"]
          }
        ],
        "icons": { "48":  "icons/icon128.jpg",
                  "128":  "icons/icon512.jpg"},
        "background": {
          "service_worker": "background.js"
        },
        "action": {},
        "permissions": [
          "storage",
          "downloads",
          "tabs"
      ]
    }
    
    // File: background.js //
    
    // Called when the user clicks on the browser action.
    chrome.action.onClicked.addListener(tab => {
        // Send a message to the active tab
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          var activeTab = tabs[0];
          chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
        });
      });
    

    (Obviously remove the comment from the .json file before copying it, and adjust the permissions of your extension appropriately.)

    Note that if you're using a version of Chrome below Chrome 93, your manifest.json and background.js must be in the SAME directory.