user219882
user219882

Reputation: 15834

JavaScript + Chrome Tabs Api - can't get tab's URL

I have the following piece of code and the problem is that the callback from chrome.tabs.getSelected is evaluated after the request which is send with empty url. How can I solve this?

function send() {
var url = '';
chrome.tabs.getSelected(null, function(tab) {
    url = tab.url;
});

var client = new XMLHttpRequest();
client.onreadystatechange = function() {
    if(this.readyState == 4) {
        alert(this.status);
    }
}
client.open("POST", "http://myurl");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

client.send(url);
}

Upvotes: 2

Views: 1946

Answers (1)

cvsguimaraes
cvsguimaraes

Reputation: 13240

Welcome to Asynchronous Programming

function send() {
    chrome.tabs.getSelected(null, function(tab) {
        var client = new XMLHttpRequest();
        client.onreadystatechange = function() {
            if(this.readyState == 4) {
                alert(this.status);
            }
        }
        client.open("POST", "http://myurl");
        client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

        client.send(tab.url);
    });
}

Upvotes: 6

Related Questions