javascript chrome.tabs.getCurrent() 或 tabs.query()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26415925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:56:23  来源:igfitidea点击:

chrome.tabs.getCurrent() or tabs.query()

javascriptgoogle-chrome-extension

提问by Jacob Edward

Both methods are producing the same error Uncaught TypeError: Cannot read property 'query' of undefinedfor my content script... I've already looked at How to fetch URL of current Tab in my chrome extension using javascriptand How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?though I'm still not sure what I'm doing incorrectly.

这两种方法都Uncaught TypeError: Cannot read property 'query' of undefined为我的内容脚本产生了相同的错误......我已经看过如何使用 javascript 在我的 chrome 扩展中获取当前标签的 URL以及如何使用 chrome.tabs.getCurrent 来获取页面对象Chrome 扩展程序?虽然我仍然不确定我做错了什么。

manifest.json

清单文件.json

{
  "name": "Extension Tester",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Tester",
  "permissions": [
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": ["https://www.google.com/"],
      "js": [
        "inject.js"
      ]
    }
  ]
}

inject.js

注入.js

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log(tabs[0].id);
});

or

或者

chrome.tabs.getCurrent(function (tab) {
  console.log(tab.id);
});

回答by youmu_i19

Cannot use chrome.tabsin content script,you need to use chrome.runtimeTo know the tab id of the content script, first use chrome.runtime.sendMessageto send a message, and the background page receive it.

不能chrome.tabs在内容脚本中使用,需要使用chrome.runtime要知道内容脚本的tab id,首先使用chrome.runtime.sendMessage发送消息,后台页面接收。

Using chrome.runtime.onMessage.addListener, the callback function is

使用chrome.runtime.onMessage.addListener,回调函数是

function(any message, MessageSender sender, function sendResponse) {...};

function(any message, MessageSender sender, function sendResponse) {...};

so, you will know the tab id by sender.id

因此,您将通过以下方式知道标签 ID sender.id