0

I'm starting out with building a Chrome extension and it looks like most of the functions there are asynchronous that use a callback function, even the ones where one would expect synchronous behavior, like chrome.tabs.getCurrent.

So, say I want to have a popup for a browserAction, and when the user clicks on a button to transfer some object as a message to background.js. That object should contain, for the purposes of this example, the current's tab URL and a cookie value. Both chrome.tabs.getCurrent(cb) and chrome.cookies.get(details, cb) require a callback. How do I collect the data to pass without doing something like the following:

chrome.tabs.getCurrent(
   function(currentTab){
      var url = currentTab.url;
      chrome.cookies.get({...}, 
         function(cookie){
             var msg = { "url" : url, "value" : cookie.value };
             chrome.runtime.connect().postMessage(msg);
         });
   }
);
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • [I recommend looking into promise objects](http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/). – zzzzBov Aug 05 '13 at 16:22
  • One way to avoid nested callbacks is through [Promises](http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/), but if the API doesn't provide that, you may have to roll your own implementation. – Vivin Paliath Aug 05 '13 at 16:22
  • @zzzzBov, so would that work for chrome extension development. Doesn't look like they support promise objects – New Dev Aug 05 '13 at 16:25
  • @NewDev, you'd have to use a promise object implementation. It's not a native browser feature. – zzzzBov Aug 05 '13 at 16:27
  • @Bergi, I guess the question could be restated as "are promises possible/available for chrome extension development?" – New Dev Aug 05 '13 at 16:32
  • …and if you don't want promises, have a look at [this question](http://stackoverflow.com/questions/5265743/node-js-what-techniques-are-there-for-writing-clean-simple-callback-code) as well. – Bergi Aug 05 '13 at 16:35
  • @NewDev: Yes, just import a library like Q and use it. Btw, I'm not sure whether they would be of much help for the posted example code, as nesting seems unavoidable there (you're accessing both `url` and `cookie` from the innermost callback) – Bergi Aug 05 '13 at 16:38
  • @Bergi, yes, that's because I need to collect the data before posting. Thanks everyone, I think I have enough to go by. – New Dev Aug 05 '13 at 16:41

0 Answers0