How to Avoid Switch To Window in Selenium WebDriver
How to avoid Switch to window concept in selenium makes you switch between different windows without using “Switch to window” method. Let’s discuss in detail.
In Many Real time scenarios, When we click on a link we see many of those opens in new tab or new windows. We generally use the switchtowindow concept from selenium and handle it. We need to be cautious while switching window and we should always switch back the driver focus to the old window when we need to handle the operation on the parent window. Please click this link for the example.
However, We can handle it in a different way to open the link in the same tab. We use JavaScriptExecutor to alter attributes for the DOM and we open the link in the same tab. Using JavaScriptExecutor we alter target attribute value and then we click on the link. Which makes links open in the same Tab. For navigation to back window we use navigate commands in selenium. This is a pretty easy way to handle different screens originating from the same application.
Sample Code:
import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class AvoidSwitchToWindow { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("http://demo.automationtesting.in/Windows.html"); String mainWindowTitle = driver.getTitle(); System.out.println("Main Window Title is: "+mainWindowTitle); WebElement we = driver.findElement(By.cssSelector("a[href='http://www.sakinalium.in']")); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("arguments[0].setAttribute('target','_self');",we); we.click(); String childWindowTitle = driver.getTitle(); System.out.println("Child Window Title is: "+childWindowTitle); driver.navigate().back(); mainWindowTitle = driver.getTitle(); System.out.println("Main Window Title is: "+mainWindowTitle); } }
In the above program, we changed the target attribute from _blank to _self. So, the new window will open in the same window instead of a new window.
Please watch the YouTube video for better understanding.