且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点击Chrome扩展程序的图标

更新时间:2023-12-05 20:09:40

您可以使用两种方法:

方法1:使用后台脚本.

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?');
});
 

方法2:使用弹出窗口. 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?');
 

您的问题是您将两者混在一起.如果您使用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:

Approach 1: Use a background script.

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?');
});

Approach 2: Use a popup. manifest.json:

"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.)