简体   繁体   English

无法使用 JavaScript 在 Chrome 浏览器中关闭选项卡

[英]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()");我无法在下面的代码js.executeScript("window.close()");使用 JavaScript 最后一行关闭 Chrome 浏览器中的选项卡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()");

    }

}

By invoking js.executeScript("window.close()");通过调用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.要关闭弹出窗口,您需要以某种方式定位它或在JavascriptExecutor上下文中保存对它的引用。

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

You can also try getWindowHandles() and getWindowHandle()你也可以试试getWindowHandles()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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM