2013-03-24 65 views
0

我一直在尝试在后台页面中发送搜索历史并将回复发回到首页。我正在使用消息解析。 搜索历史记录后,我无法发送回应。在历史搜索传递消息时发送回复

-------- ------------- background.js

var SECONDS_PER_WEEK = 1000 * 60 * 60 * 24 * 7; 

chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) { 
    if(request === "getHistory"){ 
     var value = getHistory(); 
     console.log("Response" , value); 
     sendResponse(value);  
} 
} 

);

function getHistory(){ 
var current_time = new Date().getTime(); 
var timeToFetch = current_time - SECONDS_PER_WEEK; 
return chrome.history.search({ 
     'text' : '', 
     'startTime' : timeToFetch 
    }, 
    function(resp){ 
     return resp; 
}); 

}

问题就出在这里本身就记录我得到“未定义”作为响应。 谁能告诉我去解决

回答

0

大多数Chrome.* API函数是异步的所以尝试做这样的事情:

background.js

var SECONDS_PER_WEEK = 1000 * 60 * 60 * 24 * 7; 

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
    if(request === "getHistory"){ 
    getHistory(sendResponse); 
    return true; 
    } 
}); 

function getHistory(sendResponse){ 
    var current_time = new Date().getTime(); 
    var timeToFetch = current_time - SECONDS_PER_WEEK; 
    chrome.history.search({ 
    'text' : '', 
    'startTime' : timeToFetch 
    }, 
    function(resp){ 
    console.log("Response: " + resp); 
    sendResponse(resp); 
    }); 
}