Alon Mahl Alon Mahl - 4 months ago 34
Javascript Question

chrome extension chrome.browserAction.onClicked doesnt work

I am trying to write a simple extension that will redirect me from a specific page to another url when clicking on the browser action icon.

I am trying to use:

chrome.browserAction.onClicked.addListener


but I get


Uncaught TypeError: Cannot read property 'onClicked' of undefined


This is my manifest file:

{
"name": "first extension",
"version": "2.2.12",
"description": "redirct to a link icon",
"browser_action": {
"default_icon": "icontest.png",
"default_title": "Do action"
},
"permissions": ["tabs", "http://*/*"],
"content_scripts": [{
"matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"],
"js": ["twterland.js"]
}],
"icons": {
"16": "icontest.png",
"48": "icontest.png",
"128": "icontest.png"
}
}


This is my js file:

chrome.browserAction.onClicked.addListener(function(tab) { alert("hi"); });

Answer

It seems like the code is in your twterland.js file, which is your content script. browserAction can only be used in extension pages, so you can not use it in content scripts.

Document: https://developer.chrome.com/extensions/content_scripts

However, content scripts have some limitations. They cannot:
- Use chrome.* APIs (except for parts of chrome.extension)
- Use variables or functions defined by their extension's pages
- Use variables or functions defined by web pages or by other content scripts

Put it on the background page instead.