How to open a new tab immediately after the current tab?

I am developing a chrome extension and I want to open a new tab, but after the current tab in which the user is enabled. This is what I tried to do:

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

but the created tab opens at the end of the tab queue in the Chrome tab bar. After removing 'index': id from chrome.tabs.create result will be the same. I do not know how to solve the problem. Can anybody help me?

+4
source share
2 answers

A tab is added at the end because you are using the wrong argument ( id must be index ). tab id is a positive integer that uniquely identifies the tabs in the session. Therefore, the id value is always greater than the number of tabs.

The position of the tab can be read from the index property. So, replace id with index :

 function clickEvent(info, tab) { update(); var url = "http://google.com/"; var index = tab.index + 1; chrome.tabs.create({'url': url, 'index': index}); } 
+3
source

It looks like you are creating a “baby” tab, in which case you should set both index and openerTabId :

 function addChildTab(url, parentTab) { chrome.tabs.create({ 'url': url, 'windowId': parentTab.windowId, 'index': parentTab.index + 1, // nb index not id 'openerTabId': parentTab.id // nb id not index }); } 

Setting openerTabId means that the new tab will be correctly associated as a child tab of the parent tab, therefore:

  • If you close the child tab while it is active, the parent tab will become the active tab (and not, say, the tab to the right of the child tab). This makes it behave the same way as links that the user opens on new tabs.
  • Extensions that display tabs in the tree will work correctly .

See also https://code.google.com/p/chromium/issues/detail?id=67539 who added this.


Note: if you open a tab in the background (passing active:false ), then parentTab.index + 1 not entirely correct, and instead you should insert a new tab after the existing child (and grandson) tab of 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 }); }); } 

But this may be redundant for your purposes, in which case sticking to parentTab.index + 1 , as in my first code example, should be fine.

+6
source

All Articles