views:

136

answers:

1

Hi All, Having a problem while passing messages using content scripts in Google chrome extension dev My Code structure looks like this:

popup.html:

var oList;
function getHTML()
{
    chrome.tabs.getSelected(null, function(tab) {
     chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
      oList = response.dom;
     });
   });

   alert("oList = "+oList );
}

and my content Script looks like this:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
  if(request.action == "getHTML"){
   sendResponse({dom: document.getElementsByTagName("HTML").length});   
     }
  });

When I debug my code by putting a breakpoint at "oList = response.dom;" in my popup.html, i get the right value set from the content script. But while executing the extension, the "alert("oList = "+oList );" code from the popup.html seems to be executing first before it goes to the server.. And therefore, its value is not being set.. Can somebody tell me if I am wrong somewhere ?

+4  A: 

Most Chrome API methods are asynchronous. It means that when you are calling them the script doesn't wait for their response and simply continues executing. If you want to execute something on response you should put it inside callback function:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
  oList = response.dom;
  alert("oList = "+oList );
 });
});
serg
Thank you.. But thats what I am doing right ? My 'sendRequest' has the code 'oList = response.dom;' which should set the value to oList. This is getting set while debugging it, but not while executing it :(
paypalcomp
I add a console.log("oList = "+oList);. But I see the result in the console only when I debug.. Not when I execute :(
paypalcomp
@paypalcomp That's not what you are doing. Your assignment doesn't happen before display. Imagine that you have very big amount of data to transfer and it would take 1 hour. Your code would execute in such order: `var oList;` immediately followed by `alert(oList);` (it doesn't wait for data to load), then 1 hour later: `oList = response.dom;`. Now your amount of data is smaller so it takes only few milliseconds for callback to get triggered, but it still happens few milliseconds later than your alert.
serg
Ok.. cool.. Thanks for the reply guys :)
paypalcomp