3

I'm not able to close tab in chrome browser using JavaScript last line in below code js.executeScript("window.close()"); is not working. Can any one please help on the issue?

package TestCode; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Chrome { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver","C:\\Akash\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.gmail.com"); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.open('https://www.facebook.com')"); Thread.sleep(5000); js.executeScript("window.close()"); } } 
2
  • Actually this way you can not close other window.. you need to switch that window first by finding all open window as driver.windowHandles and then close that window as driver.close().. follow this link..CommentedAug 25, 2017 at 11:40
  • This might help stackoverflow.com/questions/18493572/…
    – Naman
    CommentedAug 25, 2017 at 11:41

2 Answers 2

5

By invoking js.executeScript("window.close()"); you are trying to close the main window, not which you have just opened. To close popup window you need to locate it somehow or save the reference to it in the JavascriptExecutor context.

Note, that global variables there should be preserved:

Note that local variables will not be available once the script has finished executing, though global variables will persist.

So you could try to do the following:

 JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("popup_window = window.open('https://www.facebook.com')"); Thread.sleep(5000); js.executeScript("popup_window.close()"); 
    1

    You can also try getWindowHandles() and getWindowHandle()

    String parentWindow=driver.getWindowHandle(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Pass a window handle to the other window for(String childWindow: driver.getWindowHandles()){ if(!childWindow.equals(parentWindow)) { System.out.println("child"); //switch to child window driver.switchTo().window(childWindow); //Your operations driver.close(); } } System.out.println("Come to parent window"); //switch to Parent window driver.switchTo().window(parentWindow); 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.