Javascript Chrome扩展-奇怪的执行顺序

Javascript Chrome扩展-奇怪的执行顺序,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在写一个小的Chrome扩展 在我的background.html中,我有以下内容: <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(

我正在写一个小的Chrome扩展 在我的background.html中,我有以下内容:

<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>
ins0
ins5
ins1
tab_id: -1
ins2
ins3
ins6
所以它看起来像是从代码的一部分跳到另一部分。
有什么想法吗?

Chrome API调用是异步的,所以如果您想按顺序执行它们,就需要使用回调。如果您只需要获取新创建的选项卡id,则:

chrome.tabs.create({'url': 'http://myurl', 'selected': false}, function(tab){
    console.log("created tab:", tab.id);
});
更新

然后,您的
get\u tab\u id()
函数应该如下所示:

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

我需要创建一个新的选项卡-以防没有这样的选项卡已经打开。这就是为什么我逐个检查所有选项卡。另外,我还需要获取我的页面的tab_id以便进一步处理。非常感谢您的帮助,我已经通过使用回调修复了这一问题。你关于chrome扩展是异步的信息非常有用。你只是想确保你不会打开同一个页面的多个选项卡吗?不,任务不同。我已经修好了。无论如何,谢谢你。
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
}