[英]Couldn't able to get the data for the current tab
我是chrome扩展程序开发的新手,我想获取当前选项卡的内容。
我提到了这个问题。 但是我看不到它的作用。
这是我的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)
我在哪里犯错?
您是否注意到不赞成使用Request
来支持Message
。 因此,您应该使用onMessage
和sendMessage
代替sendRequest
,而不是onRequest
。 看到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.