Chrome Extension's Icon on click

会有一股神秘感。 提交于 2020-01-01 03:04:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!