I'm developing a chrome extension and I want to open a new tab, but after the current tab that user is on. This is what I've 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 tabs queue in chrome tab bar. After removing 'index': id
from chrome.tabs.create
, the result is same. I don't know how can I resolve the problem. Can anybody help me?
It sounds like you're creating a 'child' tab, in which case you should set both the index
and the openerTabId
:
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
});
}
Setting the openerTabId
means that the new tab will properly be associated as a child tab of the parent tab, hence:
See also https://code.google.com/p/chromium/issues/detail?id=67539 which added this.
Note: if you're opening the tab in the background (by passing active:false
), then parentTab.index + 1
isn't quite right, and instead ideally you'd insert the new tab after existing child (and grandchild) tabs 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 that may be overkill for your purposes, in which case sticking with parentTab.index + 1
as in my first code sample should be fine.
The tab is appended at the end because you're using the wrong argument (id
should be index
). The tab id
is a positive integer which uniquely identifies tabs within a session. Consequently, the value of id
is always higher 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});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With