Google chrome extension chrome.tabs.query事件未触发

Google chrome extension chrome.tabs.query事件未触发,google-chrome-extension,Google Chrome Extension,我最近一直在尝试使用chrome扩展,现在我只是想熟悉ChromeAPI 具体来说,我正在测试chrome.tabs.query,以创建一个带有当前活动选项卡URL的警报,但不会触发该事件。下面是我的background.js文件的代码 chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ var activeTab = tabs[0]; var activeTabUrl = activeTa

我最近一直在尝试使用chrome扩展,现在我只是想熟悉ChromeAPI

具体来说,我正在测试chrome.tabs.query,以创建一个带有当前活动选项卡URL的警报,但不会触发该事件。下面是我的background.js文件的代码

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    var activeTab = tabs[0];
    var activeTabUrl = activeTab.url;
    alert(activeTabUrl);
});
这是我的manifest.json。我很确定所有的权限都是正确的

{

    "manifest_version": 2,
    "name": "Time Tracker",
    "description": "Track how much time spent on ...",
    "version": "1.0",
    "permissions": ["history", "bookmarks", "activeTab", "tabs"],
    "background":{
      "service_worker": "background.js"
    },
    "content_scripts": [
      {
        "matches": ["http://*.www.youtube.com/*"],
        "js": ["content.js"]
      }
    ],
    "browser_action": {
        "default_popup": "popup.html",
        "default_icon": "/images/clock.png"
    }
}

我还尝试了其他chrome API,如chrome.history.onVisited,尝试添加eventListener,但似乎没有任何效果

我在这里添加了完整回购协议的链接。

更新#6月1日至2日。2021年(对最近评论的回应)

这是我最新的代码和背景脚本

function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log("Updated tab: " + tabId);
  console.log("Changed attributes: ");
  console.log(changeInfo);
  console.log("New tab Info: ");
  console.log(tabInfo);
}

chrome.tabs.onUpdated.addListener(handleUpdated);


chrome.tabs.query({active: true, currentWindow: true}, function(tabs){

    var activeTab = tabs[0];
    var activeTabUrl = activeTab.url;
    alert(activeTabUrl);
});

您可以在此处找到chrome.tabs事件的文档:

(向下滚动至末尾)


您必须在后台脚本中添加一个“onUpdate”事件。

我在后台脚本顶部的示例部分添加了第一个代码片段,只是为了测试它,但在控制台中没有看到任何内容。(滚动至底部)我真的不知道我的chrome是否有问题。让我们关注一下当页面url更改时您希望看到的警报,忘记内容脚本!你能完整地发布背景吗?我在文章的底部添加了一个更新,给出了我的background.js文件的完整内容,截止到2011年。感谢您的帮助:)我已经对manifest.json中的“content_scripts”部分和console.log(activeTabUrl)中的convert alert(activeTabUrl)部分进行了注释。警报不能再在MV3后台脚本(又名扩展服务工作者)中使用。在这几次mods之后,一切正常。我试着在一个选项卡中更改url,onUpdate事件触发正常。
function handleUpdated(tabId, changeInfo, tabInfo) {
  console.log("Updated tab: " + tabId);
  console.log("Changed attributes: ");
  console.log(changeInfo);
  console.log("New tab Info: ");
  console.log(tabInfo);
}

chrome.tabs.onUpdated.addListener(handleUpdated);


chrome.tabs.query({active: true, currentWindow: true}, function(tabs){

    var activeTab = tabs[0];
    var activeTabUrl = activeTab.url;
    alert(activeTabUrl);
});