更新时间:2023-12-05 20:09:40
您可以使用两种方法:
在manifest.json
中:
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"activeTab",
"clipboardWrite"
],
"background": {
"persistent": false,
"scripts": ["background.js"]
}
(您也可以使用"page": "background.html"
代替"scripts"
.)
background.js
中: chrome.browserAction.onClicked.addListener(function(tab) {
alert('working?');
});
"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?');
您的问题是您将两者混在一起.如果您使用browser_action.default_popup
,则chrome.browserAction.onClicked
是从不触发. (而且您不希望使用名为popup.html
的背景页面,因为这会引起各种混乱.)
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.
There are two approaches you can use:
in 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"
.)
in background.js
:
chrome.browserAction.onClicked.addListener(function(tab) {
alert('working?');
});
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"clipboardWrite"
]
in popup.html
:
<html>
<head>
<script src="popup.js"></script>
</head>
</html>
in 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.)