Get title of window without switching in selenium webdriver - selenium-webdriver

Is there any way to get window title without making any switch in selenium?
presently I'm using below code:
public boolean switchToWindowByTitle(String title){
String currentWindow = driver.getWindowHandle();
Set<String> availableWindows = driver.getWindowHandles();
if (!availableWindows.isEmpty()) {
for (String windowId : availableWindows) {
String switchedWindowTitle=driver.switchTo().window(windowId).getTitle();
if ((switchedWindowTitle.equals(title))||(switchedWindowTitle.contains(title))){
return true;
} else {
driver.switchTo().window(currentWindow);
}
}
}
return false;
}

Page Title is the <title> tag and appears at the top of a browser window which is part of the HTML DOM within the <header> section of the <html>.
So Selenium driven WebDriver needs to have the focus on the specific Browsing Context to extract the Page Title.
Where as Window Handle is a unique identifier that holds the address of all the windows and can return the string value. All the browser will have a unique window handle. This getWindowHandles() function helps to retrieve the handles of all windows.
So Selenium driven WebDriver can collect the Window Handles from the Browsing Context even without having individual focus on them.
Conclusion
So it is not possible to get the title of window/tab without switching to the specific Window / TAB.

This Code will do the purpose. Call this function as follows
swithToWindow("window Name");
public static Boolean switchToWindow(String title) {
String Parent_window = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String handle : handles) {
driver.switchTo().window(handle);
if (driver.getTitle().equalsIgnoreCase(title)) {
return true;
}
}
driver.switchTo().window(Parent_window);
return false;
}

ArrayList<String> tabs = new ArrayList<String> driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
String parentWindow=driver.getWindowHandle();
Set<String> windows= driver.getWindowHandles();
for(String child:windows){
try{
if(!child.equalsIgnoreCase(parentWindow)){
driver.switchTo().window(child);
String windowTitle=driver.getTitle();
if(windowTitle.equals("book My Show")){
System.out.println("Window found");
}
else{
System.out.println("no windows found");
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("");
}
}
driver.switchTo().window(parentWindow);
}
}

Related

Selenium Java : stale excpetion for dropdown

I am doing below steps in my test case
1.Open main page
2.Click on one link which opens a new page(tab)
3.Query data (Click on Query button. Page gets reloaded)
4.Select one drop down – “request” , fill some text data and click save
5.Close this tab
6.From Main page , again click on the link to open this page (tab)
7.Query some data ( Click on Query button . page gets reloaded)
8.Select one drop down - “response” , fill some data and click save
I am getting error at Step-8 while selecting drop-down "Response". The same drop-down while selecting “request” worked fine. Also, I am able to select “response” if I open the page only once (exclude steps- 3,4,5). What is happening here? I am new to selenium and tried almost every solution available for stale exception.
The same code is working fine in my colleagues system without any issues . ( same chrome version)
I also tried by giving sleep time . Also while execution it is expanding the drop-down and I could see the “response” , but still it is not selecting the response.
These are my code snippets. Using chrome browser.
************************ Testcase ******************************
public class TC_004 extends BaseClass{
#Test
public void TNRangeConfirm() throws InterruptedException{
driver.get(baseURL);
LoginUS login=new LoginUS();
login.loginTest();
Thread.sleep(10000);
logger.info("Starting Multiline Creation");
PageActions icp=new PageActions();
logger.info("Sending request");
icp.PortReq();
logger.info("Sending response");
Thread.sleep(5000);
icp.PortRes();
LogoutUS logout=new LogoutUS();
logger.info("Logging out");
logout.logoutTest();
}
}
*********************************************************
**********************Reusable Action***********************
public class PageActions extends BaseClass{
String currentWindow = driver.getWindowHandle();
MainMenuPage mmp=new MainMenuPage(driver);
ActionsPage ipdP=new ActionsPage(driver);
public void PortReq() throws InterruptedException{
System.out.println(" Creation Multi Line : Started");
System.out.println(" Click on Actions page");
mmp.clickPRRADM(); // It expands the link
Thread.sleep(1000);
mmp.clickIPD(); // Opens the page
Thread.sleep(60000);
//Switch tab
//ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//driver.switchTo().window(tabs.get(1));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(currentWindow)) {
driver.switchTo().window(handle);
}
}
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN1 = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
TN2 = mtd.readExcel(filePath, fileName, sheetName, "TN1");
TN3 = mtd.readExcel(filePath, fileName, sheetName, "TN2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("TN : "+TN);
ipdP.selectPortType("Request");
ipdP.setPortNo(TN);
ipdP.selectOwner(TN1);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(10000);
Boolean isPresent = driver.findElements(By.id("INFO_MSD_ID_0")).size() >0 ;
if((isPresent) && (ipdP.isExist("NO RECORDS FOUND"))){ */
System.out.println("Multi Line Creation Started");
ipdP.selectPortAction("Request");
Thread.sleep(10000);
ipdP.selectNNSP(TN1);
Thread.sleep(6000);
ipdP.selectONSP(TN2);
Thread.sleep(10000);
ipdP.clickSave();
Thread.sleep(30000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
public void PortRes() throws InterruptedException{
String currentWindow = driver.getWindowHandle();
mmp.clickPRRADM();
Thread.sleep(1000);
mmp.clickPRRADM();
Thread.sleep(5000);
mmp.clickIPD(); // opens page
Thread.sleep(30000);
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
onsp = mtd.readExcel(filePath, fileName, sheetName,"Old_Network");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create Response
System.out.println("Response Started");
//Switch tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
waitUntil wt= new waitUntil();
boolean isFound=wt.waitForElement(driver, By.id("select-REC_TYPE_ID"));
System.out.println("isFound"+isFound);
wt.waitTillDropdownElementLoads(By.id("select-REC_TYPE_ID"), "Request");
wt.waitTillListOfElementsVisibility(By.id("QRY_NUM_ID"));
Thread.sleep(40000);
ipdP.setPortNo(TN);
wt.waitTillDropdownElementLoads(By.id("select-QRY_OWNER_ID"), owner);
ipdP.selectOwner(owner);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(40000);
ipdP.selectMultiPortAction("Response"); // My code fails at this point stale excecption.
Thread.sleep(10000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
}
************************************************************************************
***********************************PageObject class ********************************
public class ActionsPage {
WebDriver ldriver;
public ActionsPage (WebDriver rdriver){
ldriver=rdriver;
PageFactory.initElements(rdriver,this);
}
#FindBy(id="select-DETAILS_ACTION_ID")
#CacheLookup
WebElement selAction;
public void selectPortAction(String action){
Select portAction = new Select(selAction);
portAction.selectByValue(action);
}
******************************************************************************************
I commented out #CacheLookup and it started working without any issues. But I dont know what is the reason behind this.
In PageObject class comment out #CacheLookup and this resolved my error.
#FindBy(id="select-DETAILS_ACTION_ID")
//#CacheLookup
WebElement selAction;

Handle event for html button codename one

In form I embedded WebBrowser component with lots of html contents (Mainly Table, buttons ) for rich ui. Is it possible to handle event on clicking html button ?
Sure, look at the kitchen sink demo for a sample.
Generally just navigate to a URL on the event and implement your own BrowserNavigationCallback to handle navigation to that specific URL.
This is the code from the Kitchen Sink demo notice the setBrowserNavigationCallback block:
final WebBrowser wb = new WebBrowser();
if(wb.getInternal() instanceof BrowserComponent) {
Button btn = new Button("Add");
final TextArea content = new TextArea();
Container north = new Container(new BorderLayout());
north.addComponent(BorderLayout.CENTER, content);
north.addComponent(BorderLayout.EAST, btn);
cnt.addComponent(BorderLayout.NORTH, north);
content.setHint("Add to web document");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
((BrowserComponent)wb.getInternal()).execute("fnc('" + content.getText() + "');");
}
});
((BrowserComponent)wb.getInternal()).setBrowserNavigationCallback(new BrowserNavigationCallback() {
public boolean shouldNavigate(String url) {
if(url.startsWith("http://sayhello")) {
// warning!!! This is not on the EDT and this method MUST return immediately!
Display.getInstance().callSerially(new Runnable() {
public void run() {
((BrowserComponent)wb.getInternal()).execute("fnc('this was written by Java code!')");
}
});
return false;
}
return true;
}
});
}

How do I get Codenameone to capture video?

I am using the following code to try to capture video with codenameone 2.0
tProperty.setHint("name the property that is a media");
final CheckBox cbVideo = new CheckBox("Video");
final Button bCapture = new Button("Capture Media");
final MediaPlayer mpPlayer = new MediaPlayer();
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect){
try {
if (cbVideo.isSelected()) {
String value = Capture.captureVideo();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}else {
String value = Capture.captureAudio();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}
}catch (Exception e){
}
}
});
cM.addComponent(tProperty);
cM.addComponent(cbVideo);
cM.addComponent(bCapture);
cM.addComponent(mpPlayer);
Command [] cmds = new Command[1];
cmds[0] = new Command("Done") {
public void actionPerformed(ActionEvent evt) {
//do Option1
}
};
Dialog.show(editType, cM, cmds);
When running in the simulator, clicking on the CaptureMedia button, it will present the file chooser interface. But then I am unable to choose any file at all whether audio or video because the choose file button is diabled.
How do I get to test the video capture in the simulator?
I think it's a layout problem, you are adding the MediaPlayer component before the video was created, so it's preferred size is 0.
Try to place the video in the border layout center so it's preferred size is ignored and the player will have enough space to display.
Try this:
final Form hi = new Form("Hi World");
hi.setLayout(new BorderLayout());
final Button bCapture = new Button("Capture Media");
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect) {
try {
final MediaPlayer mpPlayer = new MediaPlayer();
String value = Capture.captureVideo();
System.out.println("Captured Video " + value);
if (value != null) {
System.out.println("Playing Video");
InputStream is = FileSystemStorage.getInstance().openInputStream(value);
String strMime = "video/mp4";
System.out.println("Input Stream" + is.available());
mpPlayer.setName("bla");
mpPlayer.setDataSource(is, strMime, new Runnable() {
public void run() {
System.out.println("reset the clip for playback");
}
});
hi.addComponent(BorderLayout.CENTER, mpPlayer);
hi.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
hi.addComponent(BorderLayout.NORTH, bCapture);
hi.show();
There is a regression in playing local videos in the Codename One simulator although it should work on the device. The next update of Codename One will fix it but for now you can workaround it by playing from a stream which should work just fine.
Just use the FileSystemStorage class to get an InputStream to the video and invoke the appropriate playback code. Note that this is less efficient than the play via URL API so when the regression is fixed you should probably return to the URL based API.

Implementing 'waitForNewWindow' in selenium webdriver

I am trying to implement a method 'waitForNewWindow' in Java using selenium WebDriver. This method is all about waiting to check if a new window is opened. If a new window is opened in the specified time, i need to return true, else return false.
public boolean waitForNewWindow(String target) {
try {
Thread.sleep(30000);
if(driver.switchTo().window(target)!=null) {
log.info("New window is opened");
return true;
}
}catch(Exception e) {
log.debug(e);
return false;
}
return true;
}
But here, I don't want to use thread.sleep(time). The waiting time needs to be specified as below:
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
Moreover, in the above code, the control is switching to the new window, which is not expected. Can someone please provide your answers on how to implement my requirement?
the below mentioned code checks for the number of windows to appear with time out
public void waitForNumberOfWindows(final int length){
new WebDriverWait(driver, 30) {
}.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return driver.getWindowHandle().length()==length;
}
});
}
it will check for the expected number of windows to be present at that instance and will return true if the count matches with in the specified timeout(30 in above code)
You can not specify a timeout like you want. You have to use Thread.sleep().
Regarding your control moving to new window because of your below line the control is moving to new tab
driver.switchTo().window(target)
If you want to simply check if there is two windows open or not, you can write something like below
while( driver.getWindowHandle().length() != 2){
Thread.sleep(2000);
}
Finally got the implementation of waitForNewWindow method, using the WebDriverWait object as below:
try {
ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
if (wd.switchTo().window(newTarget) != null) {
log.info("New window is opened with the window id : "
+ newTarget);
driver.switchTo().window(parentHandle);
return true;
} else {
return false;
}
}
};
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
if (wait.until(e)) {
log.info("the wait for the expected condition is successful");
return true;
}
} catch (Exception e1) {
log.debug(e1);
return false;
}
Tested the same and its working fine.

WPF Page navigation

I use a custom textblock in my WPF Application, when I use it in WPF Windows it worked good but when I use it in a WPF Page it make a problem. When I click on a link in my Custom Control it browse the link and show in browser but the WPF page navigate back to another WPF Page too (first page)
namespace Dtwitter.Controls
{
public class TweetTextBlock : TextBlock
{
public TweetTextBlock()
{
}
#region Dependency properties
public string TweetText
{
get { return (string)GetValue(TweetTextProperty); }
set { SetValue(TweetTextProperty, value); }
}
// Using a DependencyProperty as the backing store for TweetText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TweetTextProperty =
DependencyProperty.Register("TweetText", typeof(string), typeof(TweetTextBlock),
new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnTweetTextChanged)));
#endregion
private static void OnTweetTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
string text = args.NewValue as string;
if (!string.IsNullOrEmpty(text))
{
TweetTextBlock textblock = (TweetTextBlock)obj;
textblock.Inlines.Clear();
textblock.Inlines.Add(" ");
string[] words = Regex.Split(text, #"([ \(\)\{\}\[\]])");
string possibleUserName = words[0].ToString();
if ((possibleUserName.Length > 1) && (possibleUserName.Substring(1, 1) == "#"))
{
textblock = FormatName(textblock, possibleUserName);
words.SetValue("", 0);
}
foreach (string word in words)
{
// clickable hyperlinks
if (UrlShorteningService.IsUrl(word))
{
try
{
Hyperlink link = new Hyperlink();
link.NavigateUri = new Uri(word);
link.Inlines.Add(word);
link.Click += new RoutedEventHandler(link_Click);
link.ToolTip = "Open link in the default browser";
textblock.Inlines.Add(link);
}
catch
{
//TODO:What are we catching here? Why? Log it?
textblock.Inlines.Add(word);
}
}
// clickable #name
else if (word.StartsWith("#"))
{
textblock = FormatName(textblock, word);
}
// clickable #hashtag
else if (word.StartsWith("#"))
{
string hashtag = String.Empty;
Match foundHashtag = Regex.Match(word, #"#(\w+)(?<suffix>.*)");
if (foundHashtag.Success)
{
hashtag = foundHashtag.Groups[1].Captures[0].Value;
Hyperlink tag = new Hyperlink();
tag.Inlines.Add(hashtag);
string hashtagUrl = "http://search.twitter.com/search?q=%23{0}";
// The main application has access to the Settings class, where a
// user-defined hashtagUrl can be stored. This hardcoded one that
// is used to set the NavigateUri is just a default behavior that
// will be used if the click event is not handled for some reason.
tag.NavigateUri = new Uri(String.Format(hashtagUrl, hashtag));
tag.ToolTip = "Show statuses that include this hashtag";
tag.Tag = hashtag;
tag.Click += new RoutedEventHandler(hashtag_Click);
textblock.Inlines.Add("#");
textblock.Inlines.Add(tag);
textblock.Inlines.Add(foundHashtag.Groups["suffix"].Captures[0].Value);
}
}
else
{
textblock.Inlines.Add(word);
}
}
textblock.Inlines.Add(" ");
}
}
public static TweetTextBlock FormatName(TweetTextBlock textblock, string word)
{
string userName = String.Empty;
string firstLetter = word.Substring(0, 1);
Match foundUsername = Regex.Match(word, #"#(\w+)(?<suffix>.*)");
if (foundUsername.Success)
{
userName = foundUsername.Groups[1].Captures[0].Value;
Hyperlink name = new Hyperlink();
name.Inlines.Add(userName);
name.NavigateUri = new Uri("http://twitter.com/" + userName);
name.ToolTip = "View #" + userName + "'s recent tweets";
name.Tag = userName;
name.Click += new RoutedEventHandler(name_Click);
if (firstLetter != "#")
textblock.Inlines.Add(firstLetter);
textblock.Inlines.Add("#");
textblock.Inlines.Add(name);
textblock.Inlines.Add(foundUsername.Groups["suffix"].Captures[0].Value);
}
return textblock;
}
static void link_Click(object sender, RoutedEventArgs e)
{
try
{
System.Diagnostics.Process.Start(((Hyperlink)sender).NavigateUri.ToString());
}
catch
{
//TODO: Log specific URL that caused error
MessageBox.Show("There was a problem launching the specified URL.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
}
change your link click method to
static void link_click(Object sender, RequestNavigateEventArgs e) {
try {
System.Diagnostics.Process.Start(e.Uri.ToString());
} catch {
//TODO: Log specific URL that caused error
MessageBox.Show("There was a problem launching the specified URL.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
} finally {
e.Handled = true;
}
}
change your
link.Click+=new RoutedEventHandler(link_Click);
to
link.RequestNavigate+=new RequestNavigateEventHandler(link_Click);
Set e.Handled=true in link_click to mark you've dealt with the link click to prevent the framework from additionally processing your link click further.
Alternatively you may be able to just set the TargetName property of Hyperlink to "_blank" and not need the process start command
The code below should make it work the same way in both cases (Page and Window)....
try this to open the hyperlink in web browser in MouseDown of the Hyperlink object.
Process.Start((e.OriginalSource as Hyperlink).NavigateUri.ToString());
e.Handled = true;
Let me know if this helps.

Resources