将内容脚本中的数组传递到Google Chrome扩展程序中的后台页面

时间:2011-06-21 06:28:23

标签: arrays google-chrome google-chrome-extension messaging

我正在撰写Google Chrome扩展程序。

我想将一个小数组从内容脚本传递到消息中的后台页面。我可以简单地引用数组名称,还是需要先从它构造一个JSON对象?

以下是代码:

在内容脚本中

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

1 个答案:

答案 0 :(得分:1)

Array是JSON对象的构造,因此除了您现在正在执行的操作之外,不需要执行任何操作。