How to switch to a different window using selenium webdriver java? - webdriver

I am trying to switch to a New window which gets displayed when I click on the Debt Pricing Template. But I am unable to do that as a result of which I am not able to proceed with further scripting... The problem is I am not able to know what should I pass in the switchTo.window() because Pricing Approval Gateway window displays and following is the HTML for the new window:
<*h1 class="pageType noSecondHeader">Pricing Approval Gateway<*/h1>
Following is the code:
LoginPage2.driver.findElement(By.linkText("TEST ORG")).click();
System.out.println("3.Select Dept pricing template button from the organization detail page.");
if(LoginPage2.driver.findElement(By.name("debt_pricing_template")).isDisplayed())
System.out.println("User should able to navigate to Dept pricing template and template display few question, user have answer these question for further navigation.");
LoginPage2.driver.findElement(By.name("debt_pricing_template")).click();
LoginPage2.driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
LoginPage2.driver.switchTo().window("bPageTitle");
Please advise what needs to be added?

I never used it because in my tests I am not using any new windows, but this should help:
Set<string> handlers = driver.getWindowHandles();
if (driver.getWindowHandles().size()>= 1){
for(String handler : handlers){
driver.switchTo().window(handler);
if (driver.getElement(By.tagName("h1")).contains("Pricing")){
System.out.println("Get focus on Popup window");
break;
}
}
}
else System.out.println("No windows founded!");
I am not quite sure with the h1 approach. So if it does not help, try before opening new window storing current window to String:
String mainWindow = driver.getWindowHandle();
Then click the link (or do something else as you are doing now) to open new window. Then to switch to the new window:
Set<string> handlers = driver.getWindowHandles();
for (String handler : handlers){
if (!handler.equals(mainWindow)){
driver.switchTo(handler);
break;
}
}
And then to switch back to original window just do:
driver.switchTo(mainWindow);
Ofcourse the driver variable is expected live instance of
WebDriver

driver.findElement(By.linkText("Go to Billing Summary")).click();
driver.findElement(By.linkText("01 Mar 2016")).click();
Thread.sleep(5000);
driver.findElement(By.linkText("AMS TAX")).click();
driver.findElement(By.linkText("00842")).click();
Set<String> instancewindow= driver.getWindowHandles();
Iterator<String> it = instancewindow.iterator();
String parent =it.next();
String child = it.next();
driver.switchTo().window(child);
driver.switchTo().frame("modalSubWindow");
driver.findElement(By.linkText("View More Vehicle Details>>")).click();
driver.switchTo().window(parent);

Related

Failure to get the stage of a dialog

http://code.makery.ch/blog/javafx-dialogs-official/ shows how to get the stage of a JavaFX-8 dialog:
// Get the Stage.
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
Alas, this does not work for me: the dialog pane (although displayed) gives null on .getScene().
Is there any other easy way to get the stage or at least the scene of an open dialog window?
The background of the question is that, under certain circumstances, need to display an Alert to the user while keeping the underlying dialog window open. Currently, that does not work due to an invalid combination of Modality values, but that's a different topic.
Hard to say for sure if you post no context code but I think the problem is the timing. You need to get the stage before you showAndWait (or at least before the dialog is closed). Try this:
public static boolean showConfirmationDialog(String contentText, String headerText) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, contentText, ButtonType.YES, ButtonType.NO);
alert.setTitle("Test");
alert.setHeaderText(headerText);
Window alertWindow = alert.getDialogPane().getScene().getWindow();
System.out.println("alertWindow.getOpacity(): " + alertWindow.getOpacity());
Optional<ButtonType> result = alert.showAndWait();
//This would cause a NullPointerException at this point:
//alertWindow = alert.getDialogPane().getScene().getWindow();
//System.out.println("alertWindow.getOpacity(): " + alertWindow.getOpacity());
return (result.get() == ButtonType.YES);
}

Is it possible to programmatically call a Chrome Custom Tab, but as "incognito mode"?

In some case, a user might not want the chrome custom tab to show up in their browsing history. Is there any way the app could tell the Chrome Custom Tab to display the webpage in incognito mode, and avoid storing that URL in the user normal browsing history?
If that's currently not possible, where could someone submit a feature request for that?
Thanks!
It is possible now. For example in C#:
try
{
string dataFolder = "C:\userFolder"; // If you need to maintain your browser session, you can configure a user data directory
string urlToOpen = "https://shalliknow.com"; // replace your url to open
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
process.StartInfo.Arguments = $"--new-window={urlToOpen} --start-maximized --incognito --user-data-dir=\"{ dataFolder}\""; // SSH new Chrome
process.Start();
}
catch (Exception ex)
{
Console.Writeline("Exception while opening link in browser");
}
The source of this code, as well as a list of command line arguments for chrome.exe can be found here:
https://shalliknow.com/articles/en-scs-how-to-open-chrome-in-incognito-mode-programmatically-in-csharp

Activity Indicator is not visible on xaml page in xamarin.forms?

I have an activity indicator on xaml page. Initially its IsVisible property is false. I have a button on page. When user click on button it calls a web service to get data. I change the value of IsVisible property to true before calling the service so that activity indicator starts to display on page and after successful calling of service I change its value to again false so that it doesn't show any more on page.
But it is not working. I know the actual problem. When we call the web service the UI thread gets block and it doesn't show the activity indicator.
How I can enable the UI thread when web service gets called so that activity indicator can show on page until we get the data?
Try making your webservice call into an async and await it.
Depending on how you've structured things you may have to use a TaskCompletionSource as the following example demonstrates.
In this example when the button is clicked, the button is made invisible, and the ActivityIndicator is set to IsRunning=True to show it.
It then executes your long running task / webservice in the function ExecuteSomeLongTask using a TaskCompletionSource.
The reason for this is that in our button click code, we have the final lines:-
objActivityIndicator1.IsRunning = false;
objButton1.IsVisible = true;
That stop the ActivityIndicator from running and showing, and also set the button back to a visible state.
If we did not use a TaskCompletionSource these lines would execute immediately after calling the ExecuteSomeLongTask if it was a normal async method / function, and would result in the ActivityIndicator not running and the button still being visible.
Example:-
Grid objGrid = new Grid()
{
};
ActivityIndicator objActivityIndicator1 = new ActivityIndicator();
objGrid.Children.Add(objActivityIndicator1);
Button objButton1 = new Button();
objButton1.Text = "Execute webservice call.";
objButton1.Clicked += (async (o2, e2) =>
{
objButton1.IsVisible = false;
objActivityIndicator1.IsRunning = true;
//
bool blnResult = await ExecuteSomeLongTask();
//
objActivityIndicator1.IsRunning = false;
objButton1.IsVisible = true;
});
objGrid.Children.Add(objButton1);
return objGrid;
Supporting function:-
private Task<bool> ExecuteSomeLongTask()
{
TaskCompletionSource<bool> objTaskCompletionSource1 = new TaskCompletionSource<bool>();
//
Xamarin.Forms.Device.StartTimer(new TimeSpan(0, 0, 5), new Func<bool>(() =>
{
objTaskCompletionSource1.SetResult(true);
//
return false;
}));
//
return objTaskCompletionSource1.Task;
}
You need to do your work in an asynchronous way. Or in other words: Use Asnyc & Await to ensure, that you UI works well during the call.
You can find more informations in the Xamarin Docs.
async and await are new C# language features that work in conjunction
with the Task Parallel Library to make it easy to write threaded code
to perform long-running tasks without blocking the main thread of your
application.
If you need further asistance, please update your question and post your code or what you have tried so far.

Opening new window in WebDriver using C#

EDIT 4:
EDIT 3
EDIT 2
string currentWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window("");
string childTitle = driver.Title;
driver.SwitchTo().Window(currentWindow);
string parentTitle = driver.Title;
the above code gives me the same title for parent window or child window.
EDIT:
<a id="ctl00_ctl00_Features_ctl03_lnkPage" class="title" target="_blank" href="websiteaddress">Stay Around</a>
how to verify the title of a newly window open and once i verified then close the opened new window?
so in my page I have a link and click on the link and it opens a new window and now I am not sure how to verify the title of that window.
here is what i have done so far.
GoToMysiteUrl();
IWebElement addtoList = driver.FindElement(By.XPath(_pageName));
addtoList.Click();
//it opens a new window
now i want to switch focus on the new window and verify the title and close the new window
back to the previous window.
The piece that most people miss when dealing with popup windows in IE is that a click on an element is asynchronous. That is to say, if you check the .WindowHandles property immediately after a click, you may lose the race condition, because you're checking for the existence of a new window before IE has had the chance to create it, and the driver has had a chance to register it exists.
Here's the C# code I would use to perform the same operation:
string foundHandle = null;
string originalWindowHandle = driver.CurrentWindowHandle;
// Get the list of existing window handles.
IList<string> existingHandles = driver.WindowHandles;
IWebElement addtoList = driver.FindElement(By.XPath(_pageName));
addtoList.Click();
// Use a timeout. Alternatively, you could use a WebDriverWait
// for this operation.
DateTime timeout = DateTime.Now.Add(TimeSpan.FromSeconds(5));
while(DateTime.Now < timeout)
{
// This method uses LINQ, so it presupposes you are running on
// .NET 3.5 or above. Alternatively, it's possible to do this
// without LINQ, but the code is more verbose.
IList<string> currentHandles = driver.WindowHandles;
IList<string> differentHandles = currentHandles.Except(existingHandles).ToList();
if (differentHandles.Count > 0)
{
// There will ordinarily only be one handle in this list,
// so it should be safe to return the first one here.
foundHandle = differentHandles[0];
break;
}
// Sleep for a very short period of time to prevent starving the driver thread.
System.Threading.Thread.Sleep(250);
}
if (string.IsNullOrEmpty(foundHandle))
{
throw new Exception("didn't find popup window within timeout");
}
driver.SwitchToWindow(foundHandle);
// Do whatever verification on the popup window you need to, then...
driver.Close();
// And switch back to the original window handle.
driver.SwitchToWindow(originalWindowHandle);
Incidentally, if you're using the .NET bindings, you have access to a PopupWindowFinder class in the WebDriver.Support.dll assembly, which uses a very similar approach to the locating popup windows. You may find that class meets your needs exactly, and can use it without modification.
GoToMysiteUrl();
IWebElement addtoList = driver.FindElement(By.XPath(_pageName));
addtoList.Click();
// Post above operation a new window would open as described in problem
// Get hold of Main window's handle
string currentWindow = Driver.CurrentWindowHandle;
// Switch to the newly opened window
Driver.SwitchTo().Window("Your Window Name");
// Perform required Actions/Assertions here and close the window
// Switch to Main window
Driver.SwitchTo().Window(currentWindow);

setting IsEditable=false for item disables save/close button but not save button?

I developed a data extender class that acts on GetItem and CheckOutItem commands to do some business-specific validation to determine whether the user should have access to modify the item or not (basically if it's past the initial "author" task in workflow, no one can edit it. by default Tridion allows "reviewers" in workflow to edit the item, which is a no-no in our business).
I am relatively certain this worked at one point, but now does not. I'm exploring what might have changed, but I thought I'd ask here in case anyone has an idea.
If the item can't be modified, I'm setting the IsEditable attribute to false. This does in fact disable the Save and Close button and Save and New button, but for some reason the Save button is enabled. I don't quite understand why there could be a difference. (I'm looking to see if someone extended the save button somehow, but I don't see that being done). Any thoughts on how the Save button would enable when the others aren't?
thanks for any suggestions,
~Warner
public override XmlTextReader ProcessResponse(XmlTextReader reader, PipelineContext context)
{
using (new Tridion.Logging.Tracer())
{
string command = context.Parameters["command"].ToString();
if (command == CHECKOUT_COMMAND || command == GETITEM_COMMAND)
{
XmlDocument xmlDoc = ExtenderUtil.GetExtenderAsXmlDocument(reader);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("tcm", Constants.TcmNamespace);
try
{
//is this a page or component?
XmlNode thisItemNode = null;
thisItemNode = xmlDoc.SelectSingleNode("//tcm:Component", nsmgr) ?? xmlDoc.SelectSingleNode("//tcm:Page", nsmgr);
if (thisItemNode == null) return ExtenderUtil.GetExtenderAsXmlTextReader(xmlDoc);
// need to impersonate system admin in order to get workflow version of item later
Session sessionSystemAdmin = Util.SystemAdminSession;
XmlAttribute idAttribute = thisItemNode.Attributes.GetNamedItem("ID") as XmlAttribute;
//if ID attribute is null, we don't have the actual object being used (just a referenced item. so, we'll ignore it)
if (idAttribute != null)
{
string itemId = idAttribute.Value;
VersionedItem tridionObject = Util.ObtainValidTridionIdentifiableObject(sessionSystemAdmin, itemId) as VersionedItem;
//logic has been moved to separate method, just for maintainablility...
//the logic may change when workflow code is finished.
bool allowSave = IsItemValidForEdit(tridionObject, nsmgr);
if (!allowSave)
{
//not the WIP ("author") task... make item read-only
Logger.WriteVerbose("setting iseditable to false for item: " + itemId);
XmlAttribute isEditableAttribute = thisItemNode.Attributes.GetNamedItem("IsEditable") as XmlAttribute;
isEditableAttribute.Value = "false";
}
}
}
catch (Exception e)
{
Logger.WriteError("problem with get item data extender", ErrorCode.CMS_DATAEXTENDER_GETITEM_FAILURE, e);
}
return ExtenderUtil.GetExtenderAsXmlTextReader(xmlDoc);
}
else
{
return reader;
}
}
}
Most of the Tridion GUI probably bases the options it presents on the so-called Allowed Actions. This is a combination of the Allow and Deny attributes that are present in list-calls (if requested) and item XML.
So at the very least you will have to remove the CheckIn and Edit action from the Allow attribute (and probably add them to the Deny attribute). If you look at the Core Service documentation (or any other Tridion API documentation: these values haven't changed in a long time) you can find an Enum called Actions that hold the possible actions and their corresponding values. The Allow and Deny attributes are simply additions of these numbers.
The CheckIn action I mention is number 2, Edit is 2048.
Update:
I have a little command line program to decode the AllowedActions for me. To celebrate your question, I quickly converted it into a web page that you can find here. The main work horse is below and shows both how you can decode the number and how you can manipulate it. In this case it's all subtraction, but you can just as easily add an allowed action by adding a number to it.
var AllowedActionsEnum = {
AbortAction: 134217728,
ExecuteAction: 67108864,
FinishProcessAction: 33554432,
RestartActivityAction: 16777216,
FinishActivityAction: 8388608,
StartActivityAction: 4194304,
BlueprintManagedAction: 2097152,
WorkflowManagedAction: 1048576,
PermissionManagedAction: 524288,
EnableAction: 131072,
CopyAction: 65536,
CutAction: 32768,
DeleteAction: 16384,
ViewAction: 8192,
EditAction: 2048,
SearchAction: 1024,
RePublishAction: 512,
UnPublishAction: 256,
PublishAction: 128,
UnLocalizeAction: 64,
LocalizeAction: 32,
RollbackAction: 16,
HistoryListAction: 8,
UndoCheckOutAction: 4,
CheckInAction: 2,
CheckOutAction: 1
};
function decode() {
var original = left = parseInt(prompt('Specify Allow/Deny actions'));
var msg = "";
for (var action in AllowedActionsEnum) {
if (left >= AllowedActionsEnum[action]) {
msg += '\n' + action + ' ('+AllowedActionsEnum[action]+')';
left -= AllowedActionsEnum[action];
}
}
alert(original+msg);
}
The solution is to really look over the entire solution and be absolutely positive that nobody snuck something in recently that messes with the Save button and is magically enabling it behind the scenes. I've re-edited the code to show how I initially had it. And it does work. It will disable the save, save/close, save/new buttons and make all fields disabled. I'm sorry that I wasted Frank's time. Hopefully having this here for historical purposes may come in handy for someone else with similar requirements in the future.

Resources