简体   繁体   中英

How to change Chrome Extension icon for only active tab with popup?

I'm making a simple chrome extension that can check HTML tags for the current active tab.

When extension icon is clicked, it shows default popup page(popup.html)

It will change the extension icon depending on results and shows the results on the popup page.

I'm using chrome.browserAction.setIcon({path: imgSrc}) code to change the icon of extension.

But that problem is that, this code change extension icon on all of another tab.

I wanna change it on only the currently active tab that was clicked extension icon.

I know that I should get the current tab id to change the ext icon for the currently active tab.

For this code chrome.browserAction.setIcon({tabId: tab.id, path: imgSrc})

But no idea how to get current active tab id on popup.js , not background.js

Can somebody help me?


here are my files

manifest.json that declares default_popup

{
    "name": "Tag Checker for ChromeExtension",
    "version": "1.0.0",
    "description": "Tag Checker for ChromeExtension",
    "manifest_version": 2,
    "permissions": [
        "activeTab",
        "storage"
    ],
    "browser_action": {
        "default_icon": {
            "16": "images/browserAction/best.png",
            "32": "images/browserAction/normal.png",
            "48": "images/browserAction/bad.png",
            "128": "images/browserAction/abnormal.png"
        },
        "default_popup": "popup.html"
    }
}



popup.html

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Tag Checker</title>
    <script src="/js/popup.js"></script>
</head>
<body>
    <span id="results"></span>
</body>
</html>



popup.js

chrome.tabs.executeScript({file: '/js/injection.js'});



injection.js

//checking tag codes will be implemented here

var imgSrc = 'images/browserAction/48.png';
chrome.browserAction.setIcon({path: imgSrc});

(function() {
  document.querySelector('#results').innerText = 'DONE';
})();

Content scripts can't do it.
Move the two lines (imgSrc and setIcon) to popup.js and specify tabId .

popup.js:

chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
  chrome.browserAction.setIcon({tabId: tab.id, path: 'images/browserAction/48.png'});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM