javascript - 无法获取当前选项卡的数据

标签 javascript google-chrome google-chrome-extension

我是 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 的替代品。参见

Is chrome.extension.onRequest deprecated?

关于javascript - 无法获取当前选项卡的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774534/

相关文章:

html - popup.html - 改变宽度?

google-chrome - 如何在 Chrome 扩展中进行 A/B 测试

google-chrome-extension - 加快 Chrome 应用程序开发过程

javascript - 纸质工具提示未显示

javascript - 避免多次点击一个 div

javascript - 当我点击不同的 DIV 时出现一个可点击的对象

javascript - 使用 jQuery Validate 避免大写输入

javascript - 无法设置属性 ... 未定义 --- 奇怪

javascript - Chrome 上的 Google Auth API Javascript idpiframe 初始化错误

javascript - Jasmine calls.length 和 callCount 未定义