How can something so simple be so impossible?
All I want to do is click the browser_action button of my extension, open a form with a couple of settings, and then cl
The previous answer does not work anymore and it took me a few hours to understand how to manage a work around. I hope this can get you going faster then me.
First, you the last method in this page (by the bottom of the page) and it is asynchronous, so remember to give it a callback. The code you need is smtg like this:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query({'active': true}, getActiveTabCallback);
});
Second, you need to understand one thing that took me some time: if you are not using a background html page you won't be able to see any console.log
in your main Chrome window. You need to go to the extension page (chrome://extensions
) and click in your extensions background page
link (yes, you don't have a background page but Chrome gives you a fake one). This type of extension (based on events) should have the manifest.json containing smtg like this:
"background": {
"scripts": ["background.js"],
"persistent": false
},
Regards!
{
"name": "Stackoverflow Popup Example",
"manifest_version": 2,
"version": "0.1",
"description": "Run process on page activated by click in extension popup",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "contentscript.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
<html>
<head>
<script src="popup.js"></script>
<style type="text/css" media="screen">
body { min-width:250px; text-align: center; }
#click-me { font-size: 20px; }
</style>
</head>
<body>
<button id='click-me'>Click Me!</button>
</body>
</html>
function clickHandler(e) {
chrome.runtime.sendMessage({directive: "popup-click"}, function(response) {
this.close(); // close the popup when the background finishes processing request
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('click-me').addEventListener('click', clickHandler);
})
console.log("chrome extension party!");
Clicking extension button with browser window opened to exampley.com
After clicking 'Click Me!' button in extension popup
http://mikegrace.s3.amazonaws.com/stackoverflow/detect-button-click.zip