How to open a new tab just after the current tab? - google-chrome

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:
If you close the child tab while it is active, the parent tab will become the active tab (rather than, say, the tab to the right of the child tab). This makes it behave the same way as links that the user opens in new tabs.
Extensions that show tabs in a tree will work properly.
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});
}

Related

chrome.tabs.onUpdated.addListener triggers multiple times

I observe that the onUpdated listener for the tabs API in Chrome does trigger multiple times.
When I refresh the existing tab, the alert pops up 3 times
When I load a different URL, the alert pops up 4 times
In the alert popup, I also see that there seem to be "intermediate" title tags.
How can I avoid this and reduce action to the final update?
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
/*
Multiple Tasks:
1. Check whether title tag matches the CPD Teamcenter title and custom success tab does not exist
2. If yes, trigger three actions:
a. move tab to new Chrome window
b. call external application to hide the window with the isolated tab
c. add custom success tag to identify that this was already processed
*/
const COMPARESTRING = "My Tab Title"
var title = tab.title;
alert(title) // this alert pops up 3 or 5 times!
/* if (title == COMPARESTRING) {
return "Match. :-)";
} else {
return "No match. :-(";
} */
});
you can do something like this
chrome.tabs.onUpdated.addListener(function (tabId, tabInfo, tab): void {
if (tab.url !== undefined && tabInfo.status === "complete") {
// do something - your logic
};
});

Titanium tabs accumulating when opening new windows

I have a list of courses in rows like this:
Whenever I click a row, a new tab is created, and a new window is added to that tab showing the course info.
Then if I press back, it goes back to the courses window, which is great, but when I click another course it adds that to the list of tabs, so it starts looking like this:
Whereas, there should only be two tabs here, the Courses tab and Get Courses tab.
In get_courses.js (the file that deals with making the rows) I have this event listener which creates a new tab every time a row is clicked (which I'm sure is where my mistake is, I'm just not sure how to fix it):
table.addEventListener("click",function(e){
var courseInfo_window = Titanium.UI.createWindow({
title:e.rowData.title,
url:'get_courseInfo.js',
courseIMISCode: e.rowData.courseIMISCode
});
var courseInfo_tab = Titanium.UI.createTab({
title:'Course Info',
window:courseInfo_window
});
Titanium.UI.currentTabGroup.addTab(courseInfo_tab);
});
Which I want to be there to create a Course Info tab, but then in get_courseInfo.js I have this, possibly redundant code:
Ti.UI.currentTabGroup.activeTab.open(courseInfo_window);
Which, in my noob mind seems necessary to open my courseInfo_window, but is accumulating the tabs in the bottom (as shown in the image earlier).
TL;DR: What do I need to do (probably in get_courses.js) to update the Course Info tab instead of opening a new tab for each row click?
You can access tabs in TabGroup through tabs property. However, it would be easier to keep reference to tab which you created outside of event listener and modify inside:
var courseInfo_tab = null;
table.addEventListener("click",function(e){
var courseInfo_window = Titanium.UI.createWindow({
title:e.rowData.title,
url:'get_courseInfo.js',
courseIMISCode: e.rowData.courseIMISCode
});
if (courseInfo_tab === null) {
courseInfo_tab = Titanium.UI.createTab({
title:'Course Info',
window:courseInfo_window
});
Titanium.UI.currentTabGroup.addTab(courseInfo_tab);
} else {
courseInfo_tab.window = courseInfo_window;
}
});

Is that any option for search tabs in chrome?

that is we have opened many tabs.In that tabs i want to search specific tab. Please tell if any ext or option or add-on in chrome or firefox.
Firefox has this functionality built in. If you just start typing in the URL bar and the first character you type is % followed by a space, the rest of what you type will be treated as a search on the titles and urls of open tabs in all Firefox windows.
I'm not sure if this is the site to be asking for help finding extensions that do end user tasks such as this so I'll answer your question explicitly as well as explain how to do it programatically.
The short answer is, yes one extension that will allow you to do this can be found here:
Tab Title Search
The long answer is, in order to find all tabs with a certain name, you need to use the chrome tabs API
I whipped up a short piece of javascript to demonstrate how to have an extension that will create a popup with a search box that you type the desired tab title into. If the tab is found, it will be listed below the search box. If you click on the listing, you will switch to the tab.
// Function to search for tabs
function searchtabs() {
chrome.tabs.query({
title: ""
},
// Callback to process results
function(results) {
// Place holder for the tab to process
var foundTab = null;
// Text to match against
var queryText = document.getElementById("textToSearchInput").value;
// Div to place divs of matched title in
var queryAnswerDiv = document.getElementById("foundTabsDiv");
// Clear the current children
while (queryAnswerDiv.hasChildNodes()) {
queryAnswerDiv.removeChild(queryAnswerDiv.lastChild);
}
// Iterate over all the results
for (var i = 0; i < results.length; i++) {
// Keep track of the tab that is currently being processed
foundTab = results[i];
// If we have a title containing our string...
if (foundTab.title.indexOf(queryText) > -1) {
// Create a new div
var tabDiv = document.createElement("div");
// Set its content to the tabs title
tabDiv.innerHTML = foundTab.title;
// Let it know what the tabs id is
tabDiv.tabToSwitchTo = results[i].id;
// Allow for users to click on the representing div to switch to it
tabDiv.onclick = function() {
// Make the tab selected
chrome.tabs.update(this.tabToSwitchTo, {
selected: true
});
};
// Append the created div to our answer div
queryAnswerDiv.appendChild(tabDiv);
}
}
});
}
document.addEventListener('DOMContentLoaded', function() {
var inputField = document.getElementById("textToSearchInput");
inputField.focus();
inputField.onkeydown = searchtabs;
});
Also, if this is more what you are looking for rather than the extension that I linked, let me know and I can pack this extension.
Edit:
Fixed an error in using the wrong ID to get the input field as well as not getting the first letter of the title (use indexOf() > -1)
An extension that does this is Tab Hero for Chrome ($0.99 Chrome extension). It searches through all of the open tabs (across multiple windows) and offers to switch to the filtered tab. Try and see if it works for you.

Jquery cookie holds last value when deleted

Please take a look at my website: moskah.nl
If you type something in the field, save and refresh. You wull notice the cookie holds the value. Now if you click on the list it will be deleted. Now try storing multiple list and remove them again. You will see the last clicked list item will not be deleted (on refresh)
I cant figure out why that is. Also I cant give you an example on jsfiddle becuase somehow it doesnt work there. Please look at the source code of website (its very small) to get an idea of what is going on.
This piece is holding the cookie value
$('.fields a').click(function(e) {
var text = $('#inputBox').val();
var values = $.parseJSON($.cookie('myDemoCookie'));
if (!values) {
values = [];
}
values.push(text);
$.cookie('myDemoCookie',JSON.stringify(values),{expires: 7, path: '/' });
$(".jq-text").append('<li>' + text + '</li>');
e.preventDefault();
});
And this is for deleting the list:
$('.jq-text li').live('click', function(e) {
var values = [];
$(".jq-text").find('a').each(function(i, item) {
values.push($(item).text());
});
$.cookie('myDemoCookie', JSON.stringify(values), {
expires: 7
});
$(this).remove();
e.preventDefault();
});
Try this: https://github.com/tantau-horia/jquery-SuperCookie
Set the cookie:
$.super_cookie().create("name_of_the_cookie",{name_field_1:"value1",name_field_2:"value2"});
Insert values:
$.super_cookie().add_value("name_of_the_cookie","name_field_3","value3");
Delete values:
$.super_cookie().remove_value("name_of_the_cookie","name_field_1"));

Chrome Extension to Loop to Close Non-Selected Tabs

I've made this extension for Safari that closes inactive tabs on the current page
(var tabss = safari.application.activeBrowserWindow.tabs;
for (n=0; n<tabss.length; n++)
{
if(tabss[n] != safari.application.activeBrowserWindow.activeTab)
tabss[n].close();
}
)
I want to make the same for Chrome. But Chrome has a different way of doing things. I still want to run the loop on the index of tabs and close them if they aren't the selected tab. I've been able to get the length of the windows index but I don't know how to do a close tab loop that many times that will make sure not to close the selected tab. I have been able to get the length by doing this:
<html>
<head>
<script>
var targetWindow = null;
var tabCount = 0;
function start(tab) {
chrome.windows.getCurrent(getWindows);
}
function getWindows(win) {
targetWindow = win;
chrome.tabs.getAllInWindow(targetWindow.id, getTabs);
}
function getTabs(tabs) {
tabCount = tabs.length;
alert(tabCount);
}
// Set up a click handler so that we can merge all the windows.
chrome.browserAction.onClicked.addListener(start);
</script>
</head>
</html>
Gleaned from http://code.google.com/chrome/extensions/samples.html Merge Windows.
Now I want to run the loop but I can't figure out how to tell the loop not to close the selected tab. I was thinking of having the loop compare the looped tab to the tab ID of the selected window and it won't close that and move to the next tab index number in the loop.
Something like:
(
for (n=0; n<tabCount; n++)
{
if(chrome.tabs[n].id != tab.id)
chrome.tabs[n].remove();
}
)
But I don't know how to inject the current tabid as all the callback functions has this javascript hack/noob stumped. I can't introduce a variable from another function from what I understand.
This should do it:
// when a browser action is clicked, the callback is called with the current tab
chrome.browserAction.onClicked.addListener(function(curtab)
{
// get the current window
chrome.windows.getCurrent(function(win)
{
// get an array of the tabs in the window
chrome.tabs.getAllInWindow(win.id, function(tabs)
{
for (i in tabs) // loop over the tabs
{
// if the tab is not the selected one
if (tabs[i].id != curtab.id)
{
// close it
chrome.tabs.remove(tabs[i].id)
}
}
});
});
});