javascript - 将数组从内容脚本发送到后台脚本

标签 javascript google-chrome-extension

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

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;

而不是

recLink = request.sendLink;

在后台脚本中。感谢@wOxxOm 解决了这个问题。

关于javascript - 将数组从内容脚本发送到后台脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004452/

相关文章:

javascript - Chrome 警报事件每 4 秒持续触发一次

javascript - 如何使道场仪表居中

javascript - 如何在js函数中获取元素id?

javascript - 如何更改 URL 参数格式

javascript - 只需单击一下按钮即可更改网站的一部分

javascript - 如何通过 window.open() 在跨域窗口弹出窗口中操作 dom

php - PHP中的时间选择器

javascript - 如何通过 Chrome Identity 使用登录帐户

javascript - 默认弹出匹配 URL

javascript - 在 Chrome 扩展程序中捕获 Mac 媒体控制键