Chrome Extension's Icon on click

前端 未结 1 529
北海茫月
北海茫月 2021-02-05 16:55

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 do

相关标签:
1条回答
  • 2021-02-05 17:55

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

    0 讨论(0)
提交回复
热议问题