如何在当前标签之后打开新标签?

ahm*_*iee 4 google-chrome google-chrome-extension

我正在开发一个chrome扩展程序,我想打开一个新选项卡,但是在用户所在的当前选项卡之后.这就是我试图做的事情:

function clickEvent(info, tab) {
    update();
    var url= "http://google.com";
    var id = tab.id+1;
    chrome.tabs.create({'url': url, 'index': id});
}
Run Code Online (Sandbox Code Playgroud)

但是创建的选项卡会在chrome选项卡栏中的选项卡队列末尾打开.'index': id从中删除后chrome.tabs.create,结果是一样的.我不知道如何解决问题.有谁能够帮我?

Joh*_*lor 7

听起来你正在创建一个"子"标签,在这种情况下你应该设置indexopenerTabId:

function addChildTab(url, parentTab) {
    chrome.tabs.create({
        'url': url,
        'windowId': parentTab.windowId,
        'index': parentTab.index + 1, // n.b. index not id
        'openerTabId': parentTab.id   // n.b. id not index
    });
}
Run Code Online (Sandbox Code Playgroud)

设置openerTabId意味着新选项卡将正确关联为父选项卡的子选项卡,因此:

  • 如果在活动时关闭子选项卡,则父选项卡将成为活动选项卡(而不是,例如,子选项卡右侧的选项卡).这使其行为与用户在新选项卡中打开的链接的行为相同.
  • 在树中显示选项卡的扩展名将正常工作.

另请参阅https://code.google.com/p/chromium/issues/detail?id=67539添加了此内容.


注意:如果你在后台打开选项卡(通过传递active:false),那么parentTab.index + 1就不太对了,而且理想情况下你会在现有的子(和孙子)选项卡之后插入新选项卡parentTab:

function addBackgroundChildTab(url, parentTab) {
    chrome.tabs.query({'windowId': parentTab.windowId}, function(tabs) {
        var parentAndDescendentIds = {};
        parentAndDescendentIds[parentTab.id] = true;
        var nextIndex = parentTab.index + 1;
        while (nextIndex < tabs.length) {
            var tab = tabs[nextIndex];
            if (tab.openerTabId in parentAndDescendentIds) {
                parentAndDescendentIds[tab.id] = true;
                nextIndex++;
            } else {
                break;
            }
        }
        chrome.tabs.create({
            'url': url,
            'active': false,
            'windowId': parentTab.windowId,
            'index': nextIndex,
            'openerTabId': parentTab.id
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

但是这对你的目的来说可能有点过分,在这种情况下坚持使用parentTab.index + 1我的第一个代码样本应该没问题.