0

I am using chrome.tabs.query to get the current active URL, and then I want to pass it to my backend in firebase. In the following code:

function geturl() {
  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
  var tabURL = tabs[0].url;
     document.getElementById("demo").innerHTML = tabURL; //The line I changed to pass the URL to html.
   });

  fbase.set({
    title: tabURL,      // If I set this to title: "test", it works
  });

}

Now when I trigger this, nothing happens, so I checked and filled in test, which does work. This makes me think Chrome does not want me to do that. I can pass the URL to my popup.html, which does show it, but can't send it out from the popup.js. Is there a workaround for this, or do I need to work with the popup.html?

Cheers

ffritz
  • 2,180
  • 1
  • 28
  • 64
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Haibara Ai May 17 '16 at 00:36

1 Answers1

1

Because chrome.tabs.query is asynchronous.

fbase.set is called, while chrome.tabs.query is not finished executing.

You must put fbase.set inside the callback of chrome.tabs.query.

function getUrl() {

    chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {

        var tabURL = tabs[0].url;

        fbase.set({title: tabURL});
    });
}

Asynchronous vs. synchronous methods

UserName
  • 895
  • 7
  • 17