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

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

本文关键字:tabs query or getCurrent chrome      更新时间:2023-09-26

两种方法都为我的内容脚本生成了相同的错误Uncaught TypeError: Cannot read property 'query' of undefined。。。我已经学习了如何使用javascript在chrome扩展中获取当前选项卡的URL,以及如何使用chrome.tabs.getCurrent在chrome扩展中将页面对象获取?尽管我仍然不确定我做错了什么。

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);
});

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

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

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

因此,您将通过sender.id

了解选项卡id