我是Chrome扩展开发的新手,我想获取当前标签的内容。
我提到了this个问题。但我无法看到它的工作。
这是我的background.js
:
chrome.tabs.onCreated.addListener(function(tab){
console.log("Tab is been created " );
console.log(tab);
console.log(document.body.innerText)
});
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
console.log(document.body.innerText)
});
chrome.tabs.onSelectionChanged.addListener(function(tabId,changeInfo,tab){
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id, {method: "getText"}, function (response) {
console.log("Sending request ")
alltext = response.data;
});
});
});
我的内容脚本如下:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getText")
{
console.log("In the request method" + document.all[0].innerText)
sendResponse({data: document.all[0].innerText});
}
else
{
console.log("came here in the else blog")
sendResponse({});
}
});
console.log("Loaded the content ")
日志语句Loaded the content
(但我无法看到sendRequest
函数中的日志,为什么?)正在控制台上打印,这意味着内容脚本正在加载。在扩展清单文件中,我给出了所有这样的URL:
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["contentscript.js"]
}
]
但我仍然无法获取当前标签的数据。我一直得到以下例外:
Error in event handler for (unknown): TypeError: Cannot read property 'data' of undefined
at chrome-extension://gndneapginhhkepodhngcbcbknfjfobj/background.js:33:21
at disconnectListener (extensions::messaging:338:9)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.dispatchToListener (extensions::event_bindings:394:22)
at Event.dispatch_ (extensions::event_bindings:378:27)
at Event.dispatch (extensions::event_bindings:400:17)
at dispatchOnDisconnect (extensions::messaging:293:27)
我犯了错误?
答案 0 :(得分:0)
您是否注意到Request
已被弃用,而不是“Message
”。因此,您应使用onRequest
和onMessage
代替sendMessage
而不是sendRequest
。参见