javascriptgoogle-chrome-extensionweb-extension

My background.js is not recognizing tab being opened


I am writing a chrome extension to get the lyrics of the current song playing on spotify. The background.js file is not recognizing when a tab is opened.

console.log("Hi");

chrome.action.onClicked.addListener((tab) => {
  console.log("Hello"); <---------- This is not logging.
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: findTitleAndFetchLyrics,
  });
});

function findTitleAndFetchLyrics() {
  const element = document.querySelector(".eSMjmiD29Ox35O95waw6");
  if (element) {
    const trackName = element.getAttribute("title");
    if (trackName) {
      fetch(`https://lyrist.vercel.app/api/${encodeURIComponent(trackName)}`)
        .then((response) => response.json())
        .then((data) => {
          chrome.runtime.sendMessage({ lyrics: data.lyrics });
        })
        .catch((error) => {
          console.error("Error fetching lyrics:", error);
        });
    } else {
      console.error("No title attribute found for the element.");
    }
  } else {
    console.error("Element not found.");
  }
}

Solution

  • Try to use chrome.tabs.onActivated.addListener or chrome.tabs.onCreated or other tab events instead of action events.