两种方法都产生相同的错误Uncaught TypeError: Cannot read property 'query' of undefined
我的内容脚本...我已经看过How to fetch URL of current Tab in my chrome extension using javascript和 How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?尽管我仍然不确定自己做错了什么。
list .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
要知道内容脚本的tab id,首先使用chrome.runtime.sendMessage
发送消息,后台页面接收。
使用chrome.runtime.onMessage.addListener
,回调函数为
function(any message, MessageSender sender, function sendResponse) {...};
因此,您将通过 sender.id
知道选项卡 ID
关于javascript - chrome.tabs.getCurrent() 或 tabs.query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415925/