代码之家  ›  专栏  ›  技术社区  ›  DamilolaOwonibi

我的background.js无法识别正在打开的选项卡

  •  0
  • DamilolaOwonibi  · 技术社区  · 11 月前

    我正在写一个chrome扩展,以便在spotify上播放当前歌曲的歌词。打开选项卡时,background.js文件无法识别。

    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.");
      }
    }
    
    1 回复  |  直到 11 月前
        1
  •  0
  •   Mykhailo Svyrydovych    11 月前

    尝试使用chrome.tabs.onActivated.addListener或chrome.tables.onCreated或其他选项卡事件,而不是操作事件。