chrome.tabs.getCurrent()或tabs.query() [英] chrome.tabs.getCurrent() or tabs.query()

查看:640
本文介绍了chrome.tabs.getCurrent()或tabs.query()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法都对我的内容脚本产生相同的错误Uncaught TypeError: Cannot read property 'query' of undefined ...我已经看过您如何使用chrome.tabs.getCurrent来获取Chrome扩展程序中的页面对象?,但是我仍然不确定自己做错了什么.

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

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

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发送消息,然后背景页面就会接收该消息.

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.

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

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

因此,您将通过sender.id

这篇关于chrome.tabs.getCurrent()或tabs.query()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆