I am writing a small Chrome extension and in my background.html I have the following:
<script type="text/javascript" src="jquery.js"></script>
<script>
var hash = '';
var tab_id = -1;
var block;
tab_id = get_tab_id();
//no myurl page is opened
if(tab_id == -1)
{
chrome.tabs.create({'url': 'http://myurl', 'selected': false});
tab_id = get_tab_id();
}
function get_tab_id()
{
var tab_id = -1;
//find the needed page and get id
alert('ins0');
// get the current window
chrome.windows.getCurrent(function(win)
{
alert('ins1');
// get an array of the tabs in the window
chrome.tabs.getAllInWindow(win.id, function(tabs)
{
alert('ins2');
for (i in tabs) // loop over the tabs
{
alert('ins3');
// if the tab is not the selected one
if (tabs[i].url == 'http://myurl')
{
alert('ins4');
//get tab id
tab_id = tabs[i].id;
}
}
});
});
alert('ins5');
alert('tab_id: ' + tab_id);
alert('ins6');
return tab_id;
}
</script>
The stra开发者_运维技巧nge is that when I launch the extension - the order of alerts is the following:
ins0
ins5
ins1
tab_id: -1
ins2
ins3
ins6
So it looks like it is jumping from one part of the code to the other. Any ideas?
Chrome API calls are asynchronous, so if you want to execute them in order you need to use callbacks. If all you need is to get newly created tab id then:
chrome.tabs.create({'url': 'http://myurl', 'selected': false}, function(tab){
console.log("created tab:", tab.id);
});
UPDATE
Your get_tab_id()
function then should look like this:
function get_tab_id(url, callback)
{
var id = -1;
chrome.tabs.getAllInWindow(null, function(tabs)
{
for (var i=0;i<tabs.length;i++)
{
if (tabs[i].url == url)
{
id = tabs[i].id;
break;
}
}
callback(id);
});
}
Usage:
var tab_id = -1;
get_tab_id('http://myurl', function(id){
console.log(id);
if(id == -1) {
chrome.tabs.create({'url': 'http://myurl', 'selected': false}, function(tab){
console.log("created tab:", tab.id);
tab_id = tab.id;
restOfCode();
});
} else {
tab_id = id;
restOfCode();
}
});
function restOfCode() {
//executed after tab is created/found
}
精彩评论