0

I have a minor problem understanding jQuery deferred and promise which I would like to use for a Chrome extension I am developing for the first time. I want to be able to detect within the popup wether the current tab is Facebook.com or not. I know there might be simpler ways but I would like to learn deferred and promises along the way. It is just a test project. Sorry for my bad English and every comment is much appreciated! Thanks in advance. Below you will find my code...

function getCurrentTabUrl(callback) {
  // https://developer.chrome.com/extensions/tabs#method-query
  alert("hmm");
  var dfd = $.Deferred();
  var queryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(queryInfo, function(tabs) {
    alert(tabs[0].url);
    if(callback(tabs[0].url)) {
      dfd.resolve();
    } else {
      dfd.reject();
    }
  });

  return dfd.promise();

}


document.addEventListener('DOMContentLoaded', function() {

  var callback = function getCurrentTab(tab){
        alert("ök");
        if(tab == "https://www.facebook.com/") { return true; }
        else { return false; }

  }

  getCurrentTabUrl(callback).done(function () {
      alert('on facebook');
      $('.section').hide();

      $('.navitem').on('click', function () {
        var value = $(this).html().toLocaleLowerCase();
        $('.section').hide();

        $('#'+value).show();
      });


  }).fail(function () {
    alert('not on facebook');
  });
});
Niels Vermeiren
  • 238
  • 3
  • 10

1 Answers1

1

Basically what you are trying to do is to "turn" a function with a callback to act as a promise but you are doing it wrong.

Try this:

function getCurrentTabUrl(callback) {
    return new Promise(function (resolve, reject) {
        // https://developer.chrome.com/extensions/tabs#method-query
        alert("hmm");
        var queryInfo = {
            active: true,
            currentWindow: true
        };

        chrome.tabs.query(queryInfo, function (tabs) {
            alert(tabs[0].url);
            if (callback(tabs[0].url)) {
                resolve();
            } else {
                reject();
            }
        });
    });
}

More stuff in here.

Community
  • 1
  • 1
chenop
  • 4,743
  • 4
  • 41
  • 65
  • Hey thank you very much, this is a step in the right direction. I still can't figure out how to display this is facebook or this is not facebook though. Thanks for your help so far, really cool! – Niels Vermeiren Jan 14 '17 at 22:21
  • Thanks again man with the help of some resources it totally worked. Now I learned something and I know there are multiple ways of doing it. So confusing, thanks for your wisdom. – Niels Vermeiren Jan 14 '17 at 22:48