title: Selenium & Node.js: Switching to Created Tab dynamically
body: <p>In the case of 1 tab, the newest tab will always be the last tab.
  Same applies if it is the last tab that is used to open a new tab.
  The following code will switch to last tab.</p>
  
  <p><strong>EDIT</strong> : Thanks to @JimEvans<br/>
  In most answers on SO, you will find hardcoded indexes for windows. Like below:</p>
  
  <pre class="lang-js prettyprint-override"><code>return await driver.wait(async function () {
      return await driver.getAllWindowHandles().then(async function (handles) {
         // var isHandleCount2 = (handles.length == 2);
          if (handles.length &gt; 1) {
              return driver.switchTo().window(handles[handles.length - 1]);
          }
          return false;
      });
  }).then(function () {
      // Now do some stuff in new tab
  
  });
  </code></pre>
  
  <p>What about the case where we have 5 tabs, and active tab 3 opens a new tab and the new tab is launched between tab 3 and tab 4.</p>
  
  <p>How do we get the index of the newly created tab dynamically, without hardcoding its index, as in most examples on SO?</p>