I was just trying some hands on with Chrome Extension development.
The code i'm writing is simple, It accesses Fixer.io API from Background Event Page to get Forex rates and then returns those rates to Content Script.
I tried following the Question: [How to return the response from an asynchronous call? ][1]. But now I am confused and ended up with this code.
Can anybody help me understand how to achieve this ?
contentScript.js
document.addEventListener('mouseup',function(event)
                          {
    
                            //console.log("Event triggered");
                            
                            var selectedText=document.getSelection().toString(); //variable to store selected text
                            
                            if(selectedText.length)
                            {
                                console.log("Selected Text is "+selectedText);
                                
                                                         
                                var amount=1;
                                var base="USD";
                                
                                //Get the Exchange Rate from eventPage.js
                                chrome.runtime.sendMessage({amt: amount, bs: base},function(response){
                                                    console.log("Converted Amount: "+response.convert);});
                            }
});Background Event.js
function convertAmount(callback){
        
            var xhr=new XMLHttpRequest(); //creating a XMLHttpRequest Object
            xhr.open("GET","http://api.fixer.io/latest?base=INR",true); //Open async connection to the API
            
            xhr.onload=function returnResponse(){
                callback(xhr.responseText);
            }
            xhr.send(null);
    
}
function getRate(rate){
                   
            var json=JSON.parse(rate);
            convertedAmount=json.rates.USD;
            console.log("In Callback: "+convertedAmount);
            
            chrome.runtime.onMessage.addListener( function(request,sender,sendResponse){
    
            console.log("Converted Amount: "+convertAmount(getRate));
            
            sendResponse({convert: 60 });
            
            });
        }