I am trying to write a very simple Chrome extension. All it is at this point is a popup html file that tries to display an alert when the browser action icon is clicked. I am obviously doing something wrong because the alert doesn’t fire.
manifest.json
{
"name": "Simple",
"description": "Simple",
"version": "1.0",
"browser_action": {
"default_title": "Simple",
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
popup.html
<html>
<head>
<script>
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
alert("gah");
});
</script>
</head>
<body>
Hello World!
</body>
</html>
I have also tried:
<html>
<head>
<script>
function onPageLoad()
{
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
alert("gah");
});
}
</script>
</head>
<body onload="onPageLoad()">
Hello World!
</body>
</html>
UPDATE BASED UPON RESPONSES
Thank you for your response. I’ve made the following changes but is still not being called browser.Action.onClicked() (you can see that instead of an alert I am using console.log(). (The log at global scope is displayed, the one inside the callback is not).
manifest.json
{
"name": "Simple",
"description": "Simple",
"version": "1.0",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"background": {
"persistent": false,
"scripts": ["popup.js"]
},
"browser_action": {
"default_title": "Simple",
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
popup.html
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div style="white-space: nowrap">
Hello World!
</div>
</body>
</html>
popup.js
console.log("Running at global scope")
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
console.log("Running insode of addListener()");
});
chrome.browserAction.onClickedcan’t be used inside a popup. It doesn’t make much sense – you start listening for browser action icon being clicked after it was already clicked. It can be clicked again, but then popup will be closed and listener will be terminated before anything happens.chrome.browserAction.onClickedis supposed to be used on the background page and only when popup for browser action is not used:source
You should probably just write:
But I’m not sure if alerts work in a popup. Better try something like:
EDIT
There is one more thing to fix in your extension. As @Cody suggested in his answer, you shouldn’t have used inline script. It is blocked for security reasons. Take the code I suggested above and put it into a separate javascript file, then include it in
popup.htmlhead: