Switch between two windows in selenium webdriver - windows

I am getting error of NoSuchWindowException with this code.I am unable to switch back to old opened window and get back to new window
please review my code and help me.
public void TC_123617()throws InterruptedException {
driver.findElement(By.id("user_login")).sendKeys("akhil");
driver.findElement(By.id("user_pass")).sendKeys("akhil");
driver.findElement(By.id("wp-submit")).click();
Thread.sleep(3000);
driver.findElement(By.cssSelector("#awebsome_oruw-2 > ul")).click();
WebElement userStatus = driver.findElement(By.xpath(".//*[#id='awebsome_oruw-2']/ul/li[11]"));
String parentWindow = driver.getWindowHandle();
driver = new FirefoxDriver();
driver .manage().window().maximize();
driver.get("http://103.16.143.96/incis/wp-login.php");
driver.findElement(By.id("user_login")).sendKeys("manager");
driver.findElement(By.id("user_pass")).sendKeys("manager");
driver.findElement(By.id("wp-submit")).click();
for (String popUpHandle : driver.getWindowHandles()) {
if(!popUpHandle.equals(parentWindow)){
driver.switchTo().window(popUpHandle);
driver.switchTo().window(parentWindow);
}
}
}

You don't need to create a new driver instance if you want to switch between windows using driver.
Save a reference to current window. (so that you can return to perform actions on the window you started from.)
String parentWindow = driver.getWindowHandle();
Next Step, get all the windows and switch to the new window.
List<String> allWindows = driver.getWindowHandles();
for(String curWindow : allWindows){
driver.switchTo().window(curWindow);
}
Now, you can perform any action on the new window, and when done you could close it using
driver.close();
Finally, you can switch back to the parent window to continue your actions using
driver.switchTo().window(parentWindow)

Related

Windows Application Driver, error "Could not find any recognizable digits." when connecting to session (driver)

I know how to launch a windows application using the filepath to launch it and that works (working example below). I am writing tests and they work too but my question is this: If the application is running already, how do I create my "session" (often called "driver") for the currently running application?
I have read this article that explains how you would connect a new session to Cortana which is already running. It's a great example but my app is an exe that has been launched and is not part of windows and I'm getting the error "Could not find any recognizable digits.".
What am I doing wrong?
WORKING CODE THAT LAUNCHES THE APP AND CREATES THE "session":
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
protected static WindowsDriver<RemoteWebElement> session;
public static void Setup(TestContext context)
{
// Launch app and populate session
if (session == null)
{
// Create a new sessio
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", filepath /*The exeecutable's filepath on c drive*/);
//LaunchWPF app and wpf session
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
PROBLEM CODE :
[TestMethod()]
public void Common_CreateSession_ForAlreadyRunningmyApp()
{
string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
IntPtr myAppTopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("MyApp.Client.Shell"))
{
myAppTopLevelWindowHandle = clsProcess.Handle;
}
}
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("appTopLevelWindow", myAppTopLevelWindowHandle);
//Create session for app that's already running (THIS LINE FAILS, ERROR: : 'Could not find any recognizable digits.')
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
There's now an answer on github here. You can see on github I have made 3 tweaks to the answer given by moonkey124, 2 of them were obvious (my aplication name and a little sleep command), 1 of them was to adapt the answer to a WPF application under test...

I am facing issue in executing our Selenium test on safari browser on Mac machine

We are facing issue in switching to the new window on safari browser. Below is our code used for switching the window.
public void switchToWindow() {
Set<String> availableWindows = driver.getWindowHandles();
for (String strWinHandle : availableWindows) {
driver.switchTo().window(strWinHandle);
}
}
In availableWindows, it returns all window handles but instead of switching to new window, it is switching to parent window.
Above code works fine on all other browsers.
Selenium version - 3.11.0
Safari version - 11.1.1
You can try the following code.
public void switchToWindow() {
String curWinHandle = driver.getWindowHandle();
Set<String> availableWindows = driver.getWindowHandles();
for (String strWinHandle : availableWindows) {
if(!curWinHandle.equals(strWinHandle))
driver.switchTo().window(strWinHandle);
}
}

WinAppDriver OutLook New Email Elements not found

Trying to mimic (automate) email sending through outlook using WinAppDriver, the "New E-mail" element is recognized and new window opens but on the new Window the "To","CC" etc controls are not recognized.
I suspect the new windows session is not available for the driver.
try {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setPlatform(Platform.WIN10);
//capabilities.setCapability("appTopLevelWindow", "0xBB880A");
capabilities.setCapability("app", "C:\\Program Files\\Microsoft Office\\Office14\\OUTLOOK.exe");
outlookSession = new WindowsDriver(new URL("http://127.0.0.1:4723"), capabilities);
outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
} catch (MalformedURLException e) {
e.printStackTrace();
}
newEmail = outlookSession.findElementByName("New E-mail");
System.out.println("newEmail:::::: " + newEmail);
newEmail.click();
outlookSession.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
outlookSession.findElementByName("To").sendKeys("<email>"); (the 'To' element is not recognized.
I think that the problem you are facing is cause by the fact that Outlook will create a new Windows for your new email. That will result in the window not being part of your current session. The best way to address this, is probably creating a desktop session, finding your new window and then attaching a new session and then controlling your new window from there.
Hope this helps.
~Gilles
switchTo().activeElement() didn't work for me so I had to create a new session to interact with the elements on the new email page. Hopefully, this helps others who had the same issue as me
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("app", "Root");
driver = new WindowsDriver<>(new URL("http://127.0.0.1:4723"), capabilities);
You have to write the code for switching the window from outlook to New email.
Thread.Sleep(TimeSpan.FromSeconds(5));
var allWindowHandles1 = driver.WindowHandles;
driver.SwitchTo().Window(allWindowHandles1[0]);
When ever you have new window then you have to switch the control from one window to other.

How to set chrome browser window resolution in jenkins

Am running the Selenium webdriver(Maven Project) Scripts through Jenkins by calling pom.xml file. I have set below mentioned browser resolution
driver.manage().window().maximize();
Dimension defaultSize = new Dimension(2560,1440);
driver.manage().window().setSize(defaultSize);
However, while running the scripts through Jenkins, Chrome browser window is not set to the new dimension.
Note : In Local machine it's working fine..
Copied from my question - GOCD pipeline, Selenium ChromeDriver window size is not set
his issue looks to have been caused by two issues,
1- When mvn clean test is run from the IDE this process runs under your current user. However, when run by the Continuous Integration environment, the process is owned by the System process. so does not have the same access to resources.
2 When run from the IDE, chrome will pop up. When run from the CI environment I assumed that it defaulted chrome to run in headless mode. It does not, you have to set the --headless argument so my configuration that now works is as follows
public class GoogleChrome extends Base {
private static final Logger logger = LogManager.getLogger(GoogleChrome.class);
private String rootPath = System.getProperty("user.dir").replace("\\","/");
#Autowired
protected WebDriver driver;
public WebDriver startChromeDriver() {
logger.info("Chrome driver path : " + rootPath + "/../Tools/Drivers/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", rootPath + "/../Tools/Drivers/chromedriver.exe");
Map<String, Object> prefs = new HashMap<String, Object>();
logger.info("Disabling Chrome's credentials service");
prefs.put("credentials_enable_service", false);
logger.info("Disabling Chrome's password manager");
prefs.put("password_manager_enabled", false);
final String regex = "^\\D*$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(System.getProperty("user.name"));
boolean isHuman = matcher.matches();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
logger.info("Disabling Chrome's info bars");
options.addArguments("disable-infobars");
options.addArguments("--incognito");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
options.addArguments("--allow-insecure-localhost");
if (isHuman){
logger.info("Chrome starting maximized - isHuman: " +isHuman + " process run by " +System.getProperty("user.name"));
options.addArguments("--start-maximized");
} else {
logger.info("Chrome starting headless - isHuman: " +isHuman + " process run by " +System.getProperty("user.name")) ;
options.addArguments("--headless");
options.addArguments("--window-size=1980,1080");
}
options.setAcceptInsecureCerts(true);
try {
logger.info("Killing Chrome browser");
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
} catch (IOException e) {
logger.error("Task Kill IOException : " + e.getMessage());
}
logger.info("Starting Chrome browser...");
sleep(2);
driver = new ChromeDriver(options);
logger.info("Window size: "+ driver.manage().window().getSize());
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
return driver;
}
}
Chrome disallows setting the size larger than the system's screen resolution width, the problem may be this in your case. Some workaround could be to maximize the window to at least have the largest window available on that system.
While sometimes old chromedriver also cause the issue
If still problem exist then you can change the resolution by chrome option as :
chromeOptions.addArguments("window-size=1936,1056");
Full code will be like :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("window-size=1936,1056");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.co.in/");
Hope it will help you :)

Create a Share button on Windows Phone 8, 8.1 and 10 (Mobile)

How can I create a Share button (that share a defined mesage to another player contact) as the below image on Windows Phone 8, 8.1 and 10 (Mobile):
To create this script to share on Android Device I use the following code:
public class ShareScript : MonoBehaviour {
string subject = "Subject";
string body = "Body";
public void OnAndroidTextSharingClick()
{
StartCoroutine(ShareAndroidText());
}
IEnumerator ShareAndroidText()
{
yield return new WaitForEndOfFrame();
//execute the below lines if being run on a Android device
#if UNITY_ANDROID
//Reference of AndroidJavaClass class for intent
AndroidJavaClass intentClass = new AndroidJavaClass ("android.content.Intent");
//Reference of AndroidJavaObject class for intent
AndroidJavaObject intentObject = new AndroidJavaObject ("android.content.Intent");
//call setAction method of the Intent object created
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
//set the type of sharing that is happening
intentObject.Call<AndroidJavaObject>("setType", "text/plain");
//add data to be passed to the other activity i.e., the data to be sent
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
//intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TITLE"), "Text Sharing ");
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), body);
//get the current activity
AndroidJavaClass unity = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
//start the activity by sending the intent data
AndroidJavaObject jChooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intentObject, "Share Via");
currentActivity.Call("startActivity", jChooser);
#endif
}
}
Call DataTransferManager.ShowShareUI to show the sharing pane.
Handle the DataTransferManager.DataRequested event to provide the data when the user choses to share.
private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Share Text Example";
request.Data.Properties.Description = "An example of how to share text.";
request.Data.SetText("Hello World!");
}
See the Share data docs on MSDN for more info.
In Unity you can call these in an #if NETFX_CORE block so it runs only when using the Windows Runtime and not Mono. See Windows Store Apps: WinRT API in C# scripts. If you target Windows 10 then there are plug-ins at https://github.com/microsoft/unityplugins which include sharing. For earlier targets there are commercial plugins.

Resources