Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.browserAction.onClicked.addListener Not working

I am creating a chrome extension, but my browser action is not working.

My Manifest.jason

 {
    "name": "TypoSaurus",
    "version": "0",
    "description": "TypoSaurus extension",
    "background": {
        "page": "background.html"
    },
    "manifest_version": 2,
    "browser_action": {
        "name": "TypoSaurus",
        "icons": ["icon.png"],
        "default_icon": "icon.png"
    },
    "content_scripts": [{
            "js": ["jquery-2.0.2.min.js", "background.js"],
            "css": ["customStyles.css"],
            "matches": ["http://*/*", "https://*/*"]
        }],
    "permissions": ["<all_urls>"]
}

and my background.js

function typo (tab) {

  alert('test');
}

chrome.browserAction.onClicked.addListener(typo);

The error that I am receiving is

Uncaught TypeError: Cannot read property 'onClicked' of undefined

like image 432
Binney C Avatar asked Feb 12 '23 09:02

Binney C


1 Answers

Naming a script background.js does not magically make it a background script!

It's still defined as a content script in you manifest, and content scripts have severely restricted access to Chrome API. This causes the error you're experiencing.

Listeners for events like clicking the button should be done from one central location; this is the purpose of a background page (on better, an event page). You should declare your script as such, and broadcast a message to the content scripts if you need it.

All in all, please read the Architecture Overview carefully, it will help you a lot.

like image 182
Xan Avatar answered Feb 13 '23 21:02

Xan