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");
clien开发者_C百科t.send(url);
}
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);
});
}
精彩评论