title: Chrome Extension to Loop to Close Non-Selected Tabs
body: <p>I've made this extension for Safari that closes inactive tabs on the current page</p>
  
  <pre><code> (var tabss = safari.application.activeBrowserWindow.tabs;
  
              for (n=0; n&lt;tabss.length; n++) 
                {
            if(tabss[n] != safari.application.activeBrowserWindow.activeTab)
  
           tabss[n].close();
               }
      )
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;script&gt;
      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);
      &lt;/script&gt;
    &lt;/head&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Gleaned from <a href="http://code.google.com/chrome/extensions/samples.html" rel="nofollow">http://code.google.com/chrome/extensions/samples.html</a> Merge Windows.</p>
  
  <p>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.</p>
  
  <p>Something like:</p>
  
  <pre><code>(
              for (n=0; n&lt;tabCount; n++) 
                {
            if(chrome.tabs[n].id != tab.id)
  
           chrome.tabs[n].remove();
               }
  )
  </code></pre>
  
  <p>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.</p>