问题
I'm having a difficult time understanding how to have some JS to run when the chrome extension icon has been clicked. I'd like to for example, read some properties from the document, when the icon has been clicked.
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"clipboardWrite"
]
And inside the popup.html, I have the following:
chrome.browserAction.onClicked.addListener(function(tab) {
alert('working?');
});
But, this doesn't appear to be working. I tried having the JS above inside a background script (inside manifest.json) but that didn't work either.
回答1:
There are two approaches you can use:
Approach 1: Use a background script. manifest.json:
"browser_action": {
"default_icon": "icon.png",
},
"permissions": [
"activeTab",
"clipboardWrite"
],
"background": {
"persistent": false,
"scripts": ["background.js"]
}
(You can also use "page": "background.html"
instead of "scripts"
.)
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
alert('working?');
});
Approach 2: Use a popup. manifest.json:
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"clipboardWrite"
]
popup.html:
<html>
<head>
<script src="popup.js"></script>
</head>
</html>
popup.js:
alert('working?');
Your problem was that you were mixing the two. If you use a browser_action.default_popup
, then chrome.browserAction.onClicked
is never triggered. (And you wouldn’t want a background page named popup.html
, since that would cause all sorts of confusion.)
来源:https://stackoverflow.com/questions/31307514/chrome-extensions-icon-on-click