首页 > 解决方案 > Looking for a way to have chrome extension badge popup before clicking on extension?

问题描述

I was looking for a way to have a chrome extension badge pop up when a certain web page is visited without having to click on the extension itself. A function similar to how the extension "Honey" will pop up a badge with a green number when visiting a retail website without needing to click anything.

My code below will read the current url of a website and execute the code only once the extension is clicked which then will show the badge. The badge will then continue to stay up until I reclick the extension again. I was hoping to find a way for the badge to appear and disappear immediately when visiting and leaving a specific page.

Side Note: I was speculating that the extension needs to be active before being clicked but I am not totally sure. I am using Manifest V3.

chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => {
  let url = tabs[0].url;
  console.log(url);
 

  chrome.storage.sync.get(["web"], function (x) {
    console.log(x.web);

    if (url.includes(x.web)) {
      chrome.action.setBadgeText({ text: "!" });
      chrome.action.setBadgeBackgroundColor({ color: "red" });

    } else {
      chrome.action.setBadgeText({ text: "" });
    }
  });

});

Thank you guys for your help!

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读