0

I'm trying to make a chrome extension that gets the URL of the currently selected tab, but I'm running into a problem where I can't get the variable that the URL is stored in to return.

I've tried several things already but this is the code that I'm expecting to work:

function getStream() {
    alert(getLinking());
}

function getLinking() {
    chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        },
        function getURL(tabs) {
            var URL = tabs[0].url;
            return URL;
        }
    );
    return getURL();
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('start').addEventListener('click', getStream);
});

However it doesn't actually return anything so the alert doesn't show. Please note that it's very important for me to return the variable URL so I can use it back in the getStream function, just adding in the alert in the getURL function isn't what I'm looking for.

If anyone could help me that would be amazing, I'm not too familiar with javascript yet and I'm especially unfamiliar with chrome extension so every bit of advice could help.

Milan Karman
  • 347
  • 2
  • 8

1 Answers1

1

Method chrome.tabs.query is asynchronous, so it requires a callback to return results.

When you are working with async calls, you can handle results with any:

  • callbacks
  • Promises
  • async/await

Please check this question: How do I return the response from an asynchronous call?

According to your code, the simplest solution will be:

function getStream() {
    getLinking(function(URL) { // passing a callback 
        alert(URL)
    });
}

function getLinking(callback) { // callback - is a function that will be called when async call finished
    chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        },function(tabs) {
            callback(tabs[0].url); // run callback with a result
        }
    );
    // do not need to return anything
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('start').addEventListener('click', getStream);
});
Denis L
  • 3,209
  • 1
  • 25
  • 37