0

In popup.js in my Google Chrome extension, I have:

function sendWebResponse(hash) {
  var xmlhttp = new XMLHttpRequest(); 
  xmlhttp.open("POST", "http://localhost:3000/tasks/4123434/from_chrome");
  xmlhttp.setRequestHeader("Content-Type", "application/json");
  xmlhttp.setRequestHeader("Accept", "application/json");
  xmlhttp.setRequestHeader('Authorization', 'Token token=463c121664d98a6dafd1086e8d0ecca0');
  xmlhttp.send(JSON.stringify(hash));  
}

function grabCurrentUrl(url) {
  chrome.tabs.query(
    {'active': true, 'lastFocusedWindow': true}, 
      function (tabs) {
        var url = tabs[0].url;
        return url;
      }
)};

The following works:

function submitTrue(id) {
  sendWebResponse({"survey": id,"result": "true");
}

But the following does not:

function submitTrue(id) {
  var url = grabCurrentUrl();
  sendWebResponse({"survey": id,"result": "true", "url": url});
}

In this case, url is null. There definitely is an active tab when I do this.

Why is grabCurrentURL() not grabbing the active tab's current URL?

steven_noble
  • 4,133
  • 10
  • 44
  • 77
  • 'Why is grabCurrentURL() not grabbing the active tab's current URL?' Depends on when you're asking it to retrieve the tabs, as far as i know tabs.query is asynchron. –  Aug 04 '15 at 22:57

1 Answers1

0

So what they are all saying about it being async. You can change getCurrentUrl to be this:

function getCurrentUrl(callback) {
    chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
        if (tabs.length > 0) { 
           callback(tabs[0].url);    
        }
        return null;
    });
}

Then you change your submitTrue to be:

function submitTrue(id) {
  getCurrentUrl(function(url) {
      sendWebResponse({"survey": id,"result": "true", "url": url});
  });
}
JFo
  • 91
  • 2
  • strangely sometimes working and sometimes not -- have tried `currentWindow` instead of `lastFocusedWindow` and still sometimes working and sometimes not -- very odd -- i'm thinking that maybe (a) the pop-up becomes the last focused tab, or (b) the active tab does not have a URL at certain times, such as when the page is still loading – steven_noble Aug 05 '15 at 00:41
  • an earlier method is 100% successful in identifying the correct tab so I'm going to try storing the tab.id in a global variable and using it to retrieve the correct tab later – steven_noble Aug 05 '15 at 00:46
  • This worked, where currentTabID is a global variable: function getCurrentUrl(callback) { chrome.tabs.get(currentTabID, function(retrieveTab) { callback(retrieveTab.url); }) return null; } – steven_noble Aug 05 '15 at 01:17