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

时间:2011-01-31 07:00:22

标签: 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(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

所以它看起来像是从代码的一部分跳到另一部分。 有什么想法吗?

1 个答案:

答案 0 :(得分:2)

Chrome API调用是异步的,因此如果您想要执行它们,则需要使用回调。如果你只需要获得新创建的标签ID,那么:

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

<强>更新

您的get_tab_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);
    });
}

用法:

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
}
相关问题