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

最后都变了- 提交于 2020-06-12 02:47:24

问题


Both methods are producing the same error Uncaught TypeError: Cannot read property 'query' of undefined for my content script... I've already looked at How to fetch URL of current Tab in my chrome extension using javascript and 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.

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

or

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

回答1:


Cannot use chrome.tabs in content script,you need to use chrome.runtime To know the tab id of the content script, first use chrome.runtime.sendMessage to send a message, and the background page receive it.

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

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

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



来源:https://stackoverflow.com/questions/26415925/chrome-tabs-getcurrent-or-tabs-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!