Felix F. Felix F. - 4 months ago 16
Javascript Question

Chrome Extension - Passing URL from popup.js to Firebase

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

Answer

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