Home > Software design >  How do i click on the "Close" browser button on top right of the page with Selenium Webdri
How do i click on the "Close" browser button on top right of the page with Selenium Webdri

Time:01-26

In the application i am testing, i am inputting some data in some fields in Chrome Browser with Selenium. I want to click on the "Close" button on the top right of the page, because a notification should appear when i try to do that. However, i cannot find a way to click on that

Is there any way to simulate clicking on the "X" button in the top right of the screen?

I tried to close the browser with driver.close() but that closes the browser immediately. I need to emulate the user action of clicking on the "X" button top right.

CodePudding user response:

Because the X mark is outside the scope of HTML tree structure, you cannot inspect element and get the locator of it. And hence you cannot achieve the action of clicking X using selenium(unless you want to go with driver.close() or driver.quit()). You can try by using either some third party tool or by using java's features like Robot class. Try below code:

driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.facebook.com/");
Robot robot = new Robot();
Thread.sleep(2000);
// Press keys Ctrl   W
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_W);
// Release keys Ctrl   W
robot.keyRelease(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_CONTROL);

Try this. Note: Ctrl W shortcut is to close chrome browser, if you want to close some other browser, use the shortcut accordingly

  • Related