Switch tabs using Selenium WebDriver with Java

前端 未结 21 1598
野性不改
野性不改 2020-11-22 12:09

Using Selenium WebDriver with JAVA. I am trying to automate a functionality where I have to open a new tab do some operations there and come back to previous tab (Parent). I

21条回答
  •  鱼传尺愫
    2020-11-22 12:46

    This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:

    @Test
    public void testTabs() {
        driver.get("https://business.twitter.com/start-advertising");
        assertStartAdvertising();
    
        // considering that there is only one tab opened in that point.
        String oldTab = driver.getWindowHandle();
        driver.findElement(By.linkText("Twitter Advertising Blog")).click();
        ArrayList newTab = new ArrayList(driver.getWindowHandles());
        newTab.remove(oldTab);
        // change focus to new tab
        driver.switchTo().window(newTab.get(0));
        assertAdvertisingBlog();
    
        // Do what you want here, you are in the new tab
    
        driver.close();
        // change focus back to old tab
        driver.switchTo().window(oldTab);
        assertStartAdvertising();
    
        // Do what you want here, you are in the old tab
    }
    
    private void assertStartAdvertising() {
        assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
    }
    
    private void assertAdvertisingBlog() {
        assertEquals("Twitter Advertising", driver.getTitle());
    }
    

提交回复
热议问题