JavaScript + Chrome标签页Api - 无法获取标签的网址

时间:2011-10-05 10:24:00

标签: javascript google-chrome google-chrome-extension

我有以下代码,问题是chrome.tabs.getSelected的回调是在使用空url发送的请求之后计算的。我该如何解决这个问题?

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);
}

1 个答案:

答案 0 :(得分:6)

欢迎使用异步编程

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);
    });
}