Search code examples
arraysgoogle-chromegoogle-chrome-extensionmessaging

passing an array in a message from content script to background page in google chrome extension


I am writing a Google Chrome extension.

I want to pass a small array from a content script to background page in a message. Can I simply reference the array name or need I construct a JSON object from it first?

Here is the code:

IN THE CONTENT SCRIPT

var req;
var detailWin;

//drag off the f_foto class
var searchResult = document.getElementsByClassName("f_foto");
alert("Found Class f_foto "+searchResult.length+" times.");

//collect profile links
for (var i = 0; i<searchResult.length; ++i) 
{
    var profileLink=searchResult[i].getElementsByTagName("a");
    profileLinks[i]=profileLink[0].href;
    //  alert(i+1+" of "+searchResult.length+" "+profileLinks[i]+" length of "+profileLinks[i].length);
}
for (var i = 0; i<searchResult.length; ++i) 
{
    //tell bkgd page to open link
    chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[i]});

    //BETTER TO SEND WHOLE ARRAY.  
    //LIKE THIS? chrome.extension.sendRequest({cmd: "openProfile", urlList: profileLinks});
    //OR SHOULD I MAKE A JSON OBJECT OUT OF IT?
}

//IN THE BACKGROUND PAGE

var detailTabId = null;
var profileLinks = new Array();
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cmd == "openProfile") {
//IF RECEIVING AN ARRAY, PROCESS IT LIKE THIS?
//  profileLinks= request.urlList;
//  console.log=("Received "+ urlList.length + " links.");
        chrome.tabs.create({url: request.url}, function(tab){
        //save tab id so we can close this tab later
        detailTabId = tab.id;
        //profile tab is created, inject profile script
        chrome.tabs.executeScript(tab.id, {file: "profile.js"});
        });
    }
});

Solution

  • An Array is a construct of a JSON object so there is no need to do anything other than what you are doing now.