tabli icon indicating copy to clipboard operation
tabli copied to clipboard

FR: Sorting tabs alphabetically

Open Robert-M-Muench opened this issue 7 years ago • 0 comments

I wrote an extension for myself that sorts the tabs of the current window alphabetically, not taking www. into account. Very handy to keep related stuff in proximity to switch tabs quick.

Here is the code:

chrome.browserAction.onClicked.addListener(
  function(){ // called when we click our icon
    chrome.tabs.query( // get all tabs of the current window
      {currentWindow: true},
      function(tabs){ // called after we got all tabs
        var dict = new Map();
        tabs.forEach( // iterate through all tabs 
          function(item){ // execute for every tab
            var url = item.url.split(/http[s]?:\/\//); // get only URL, works with extensions like the great suspender

            if(url[1] && url[1].indexOf('www.') == 0){ // check if URL starts with www.
              url[1] = url[1].slice(4); // if, get rid of it - we don't want to sort by www.
            }
            dict.set(url[1], item.id); // use URL as key and tab-ID as value since we need this later
          }
        );
        var dictAsc = new Map([...dict.entries()].sort()); // sort the map alphabetically (by URL) by creating a temporary array, sorting it and assigning it to a new map
        dictAsc.forEach( // iterate through the sorted map
          function(item){ // execute per tab
            chrome.tabs.move(item, {'index' : -1}); // move tab to the end => first tab will be left after loop terminates
          }
        );
    });
  }
);

Robert-M-Muench avatar Jan 20 '18 19:01 Robert-M-Muench