0

When I send an array from content script to background script it becomes undefined in background script.
Content Script:

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
    });

Background Script:

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; 
});

Please tell me whats wrong and how do I send the array successfully.

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
  • 1
    Should be `recLink = request` because you're sending an array, not an object so it doesn't have `sendLink` property. Also you really really need to start using devtools debugger where you can set breakpoints and see what's being sent and what's being received. The background page has its [own devtools](https://stackoverflow.com/a/10258029). – wOxxOm Feb 27 '18 at 08:48
  • thanks bro wOxxOm its working now, I didn't knew about devtools debugger, I will look into it. – Vaibhav Vishal Feb 27 '18 at 09:05

1 Answers1

1

Use

recLink = request;

instead of

recLink = request.sendLink;

in background script. Thanks to @wOxxOm for solving it.

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48