【问题标题】:Sending Array from content script to background script将数组从内容脚本发送到后台脚本
【发布时间】:2019-01-08 15:46:54
【问题描述】:

当我将数组从内容脚本发送到后台脚本时,它在后台脚本中变得未定义。
内容脚本:

var sendLink = [];
var canList = document.querySelectorAll(".userName.name");
for(i=0;i<canList.length;i++)
{
    sendLink[i] = canList[i].href; 
    console.log(sendLink[i]);   //shows correct links
}
chrome.runtime.sendMessage(sendLink, function(response) {
    console.log(`message from background: ${JSON.stringify(response)}`);  // shows undefined
    });

后台脚本:

var recLink = [];
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    recLink = request.sendLink;
    sendResponse({ result: recLink[0] });   //gives error cannot read property 0 of undefined.
    chrome.tabs.create({url: recLink[0]});
    window.open(recLink[0]);
    return true; 
});

请告诉我出了什么问题以及如何成功发送数组。

【问题讨论】:

  • 应该是 recLink = request 因为你发送的是一个数组,而不是一个对象,所以它没有 sendLink 属性。此外,您确实真的需要开始使用 devtools 调试器,您可以在其中设置断点并查看发送的内容和接收的内容。背景页面有它的own devtools
  • 感谢 wOxxOm 兄弟,它现在可以工作了,我不知道 devtools 调试器,我会研究一下。

标签: javascript google-chrome-extension


【解决方案1】:

使用

recLink = request;

而不是

recLink = request.sendLink;

在后台脚本中。感谢@wOxxOm 解决它。

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多