Unable to programmatically close tab in Chrome browser through JavaScript

I need help with closing a tab in Chrome browser using JavaScript. The code snippet

js.executeScript("window.close()");
at the end of the code is not working as expected. Can someone assist me in resolving this 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()");

    }

}

Answer №1

When you use

js.executeScript("window.close()");
, you are attempting to close the main window rather than the one that was just opened. To close a popup window, you must somehow locate it or save a reference to it in the JavascriptExecutor context.

It's important to note that global variables should be maintained, as explained on Selenium's documentation:

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

To address this issue, consider the following approach:

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

    Thread.sleep(5000);

    js.executeScript("popup_window.close()");

Answer №2

If you're looking to switch between windows in Selenium, you can use the getWindowHandles() and getWindowHandle() methods.

String parentWindow=driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Switch to child window
 for(String childWindow: driver.getWindowHandles()){
   if(!childWindow.equals(parentWindow)){
      System.out.println("Switching to child window");

      // Switch to child window
      driver.switchTo().window(childWindow);
      
      // Perform operations on the child window
      driver.close();

   }
}
System.out.println("Returning to parent window");

// Switch back to the parent window
driver.switchTo().window(parentWindow);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I follow to install nodemon on my Windows 10 device?

Currently, I am utilizing the bash console on my Windows 10 system. My goal is to install nodemon using node.js, but when attempting to do so, I encounter this error message: sudo: npm: command not found It's puzzling because I should already have n ...

Looking for a jQuery fix: How can I deactivate specific items once an item is selected?

I'm currently working on a form where I need certain options to be disabled when a specific option is selected. I'm new to jQuery and could use some assistance, thank you. Check out the link here: My goal is to disable some options in the secon ...

Utilizing command handlers for economy commands in Discord.js

Recently, I’ve been diving into creating my very first economy system and command handler. So far, I've successfully integrated the '-balance' command with the command handler. However, I'm facing a challenge in integrating other comm ...

There seems to be an issue with accessing the Angular module, even though it has been clearly

While attempting to execute the code below, two errors are encountered: Error: [$injector:nomod] Module 'rooms' is not available! The module name is spelled correctly and loaded dependencies have been included. The modules are structured in the c ...

I am utilizing custom React functions to organize an array of objects according to a specified key and value parameter

My array contains a list of user objects that I want to sort based on different parameters like age and rank. I have created functions for the user to select how they want the users sorted, but the filtering functions are not working as expected. Here is m ...

Using PHP, assign a reference to a class member

Trying to create a JSON server response in PHP has been quite the task. Using an array in my output to monitor errors and successes within the script has been helpful. Take a look at the code snippet below for a better understanding. <?php $output = ar ...

ReactJS - Triggering a timeout reset and reactivation with a single button press

When I click a button that has a callback function, I want it to start a timeout with a 5-second delay. If the button is clicked again within that 5 seconds, I want the timer to reset without triggering the timeout handler. The handler should only be calle ...

What is the best way to transition sine wave patterns from the top of an image to the bottom?

I've been attempting to create a realistic wave effect on the sea, but I'm struggling to make them flow from top to bottom. No matter what adjustments I make, the waves stubbornly remain stuck at the top of the image. Below is the code snippet I& ...

Avoiding the use of thread.sleep in dynamically populated lookup field options in Selenium

I am currently working with a dynamic lookup Salesforce component on my webpage. https://i.stack.imgur.com/lxr3q.png <input lightning-basecombobox_basecombobox="" id="input-19" type="text" role="textbox" autocomp ...

Transforming XML into an HTML string with XSLT in Java

Creating a Java String instead of an external HTML file is the current goal. This can be achieved by tweaking the code as shown below: FileInputStream xml = new FileInputStream("original.xml"); FileInputStream xsl = new FileInputStream("converter.xsl"); ...

JavaScript Function Not Executed in Bottom Section

I've implemented AngularJS includes in my project. Below is the code snippet from my index.html: <!DOCTYPE html> <html ng-app=""> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> ...

Encountered an unexpected runtime error in Next.js - TypeError: Unable to access properties of null object (specifically 'tagName')

25 | const tagsList = []; 26 | for(let count = 0, index = headerEl.previousElementSibling; count < totalTags; count++, index = index.previousElementSibling){ > 27 | if (index.tagName.toLowerCase() === elementType) { | ...

Vue Dynamic Table Title

Is it possible to add labels to a pivot-table in Vue without affecting array indexes and drag-and-drop functionality as shown in the screenshot below? https://i.stack.imgur.com/5JTSM.png Are there alternative methods for implementing this feature? You c ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

Tips for managing the absence of a "No thanks" button in the sign-in popup when accessing the Google homepage with

As someone who is new to automation testing, I encountered an issue while trying to run the following code. Chrome launched successfully, but a sign-in popup appeared. public class Locators { public static void main(String[] args) { // TODO A ...

Using ng-click method with multiple arguments passed

When working on my code, I found that I like to pass two arguments to the function specified inside the ng-click attribute. <div class="shout" ng-repeat="user in users"> <p>{{user.name}}</p> <img src="media/images/delete.png" ng-cli ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Tooltip Bootstrap timing

I am currently working on creating a navigation bar with icon-only buttons that display tooltips when touched or tapped. Here is the code I have implemented: $('a[rel="tooltip"]').tooltip({ animated: 'fade', placement: ' ...

Preserve the variable alterations for future promises

I have implemented promises in my database access using elasticsearchjs, which utilizes Bluebird. Each ID in the list triggers a new query, and I need to identify the failing query by its ID. const idList = ['id1', 'id2', 'id3&apo ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...