chrome extension `sendResponse` does not work

Viewed 18156

I am writing a chrome extension but the sendResponse method does not work.

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {

            if(!request.method){
                    return false;
            }

            if(request.method=='postList' && request.post_list){
                // alert(1);                                                                                                                                                                            
                    a_facebook_api.getPostFromDB(request.post_list, function(data){
                            alert(data);                                                                                                                                                              
                            sendResponse(data);                                                                                                                                                       
                          
                    });

            } else if(request.method=='postAdd' && request.post_data){
                    a_facebook_api.addPostToDB(request.post_data, function(data){

                            sendResponse(data);
                    });

    }

            return true;

}
);

 chrome.runtime.sendMessage({method: "postList",post_list: post_list}, function(response) {

         alert(response);
                                                                                                                                                           
            });

the function alert(data) works. It gives me proper data with JSON format. However, the alert(response) does not show any message. Can anyone give me some ideas why it isn't working?

Thank you in advance!

3 Answers

I was looking for the solution to get data from content script inside the popup. Yes, you can have it with storage, but this is applied to all tabs, so better to send message to active tab, and read response:

inside popup.js

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {data: 1}, function (response) {
        console.log(response.data)
    });
});

inside content.js

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.data === 1) {
        // accepts only 1 field
        sendResponse({
            data: 2
        });
        // very important to return true 
        return true; 
    }
});
Related