我是 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 ")
日志语句已加载内容
(但我无法看到sendRequest
函数中传入的日志,为什么?)正在控制台上打印,这意味着内容脚本正在加载。在扩展 list 文件中,我给出了如下所有网址:
"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
而不是 onRequest
,并使用 sendMessage
作为 sendRequest
的替代品。参见
关于javascript - 无法获取当前选项卡的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774534/