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

时间:2014-10-17 00:10:39

标签: javascript google-chrome-extension

这两种方法都为我的内容脚本产生了相同的错误Uncaught TypeError: Cannot read property 'query' of undefined ...我已经看过How to fetch URL of current Tab in my chrome extension using javascriptHow do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?了但我仍然不确定我是什么做错了。

manifest.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

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

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

1 个答案:

答案 0 :(得分:4)

无法在内容脚本中使用chrome.tabs,您需要使用chrome.runtime 要了解内容脚本的标签ID,请先使用chrome.runtime.sendMessage发送消息,然后背景页面接收消息。

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

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

因此,您将通过sender.id

了解标签ID