Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to close tab in chrome browser using JavaScript

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()");

    }

}
like image 371
Akash Chavan Avatar asked Jun 07 '26 15:06

Akash Chavan


2 Answers

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()");
like image 96
Andremoniy Avatar answered Jun 09 '26 05:06

Andremoniy


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);
like image 32
iamsankalp89 Avatar answered Jun 09 '26 04:06

iamsankalp89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!