how to locate elements on a different webpage? - webdriver

I'm new to java and webdriver. My web-applications adds some data to a table on a webpage. If the addition is successful, a new web page is opened and the success message is displayed on the new page. If the addition is not successful, a javascript alert is thrown. After accepting the alertHow do I check the presence of an the message on the new webpage using webdriver?

If it is opening in new window you need to switch the control to new window first
Find the logic here to switch the control between windows
After switching the control to new window you can verify whatever you want. Either element or text.
isElementPresent? method logic here .
isTextPresent? method logic here.

If I understand the question correctly, after sending the data to the table, if the sending is successful then the window is loaded with a new webpage else an alert appears once you accept the alert the window is loaded.
After sending the data, check for the presence of the alert, if the alert is present then accept it. Next is verifying whether a text is present in the newly loaded webpage or not.
public void isAlertPresent(){
try {
driver.switchTo.alert().accept();
}
catch ( NoAlertPresentException e ){
}
System.out.println(driver.findElement(By.tagName("body")).getText().contains("Expected Message"));
If the location where the message appears is static then I would suggest you to use a better approach than the above like if an element has that text
WebElement element = driver.findElement(By.id("elementID"));
System.out.println(element.getText().trim().equals("Expected Message"));

Related

Print Friendly Page

So I would like to be able to have a print button for entries in our database so users can print an entry via a print friendly "form".
My thought was to create a separate page, add labels and have those labels pull the relevant information.
I know I can add the open widget information via this code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showPage(app.pages.TestPrint);
But I'm running into a few problems:
I can't get the page to open in a new window. Is this possible?
window.open(app.pages.TestPrint);
Just gives me a blank page. Does the browser lose the widget source once the new window opens?
I can't get the print option (either onClick or onDataLoad) to print JUST the image (or widget). I run
window.print();
And it includes headers + scroll bars. Do I need to be running a client side script instead?
Any help would be appreciated. Thank you!
To get exactly what you'd want you'd have to do a lot of work.
Here is my suggested, simpler answer:
Don't open up a new tab. If you use showPage like you mention, and provide a "back" button on the page to go back to where you were, you'll get pretty much everything you need. If you don't want the back to show up when you print, then you can setVisibility(false) on the button before you print, then print, then setVisibility(true).
I'll give a quick summary of how you could do this with a new tab, but it's pretty involved so I can't go into details without trying it myself. The basic idea, is you want to open the page with a full URL, just like a user was navigating to it.
You can use #TestPrint to indicate which page you want to load. You also need the URL of your application, which as far as I can remember is only available in a server-side script using the Apps Script method: ScriptApp.getService().getUrl(). On top of this, you'll probably need to pass in the key so that your page knows what data to load.
So given this, you need to assemble a url by calling a server script, then appending the key property to it. In the end you want a url something like:
https://www.script.google.com/yourappaddress#TestPage?key=keyOfYourModel.
Then on TestPage you need to read the key, and load data for that key. (You can read the key using google.script.url).
Alternatively, I think there are some tricks you can play by opening a blank window and then writing directly to its DOM, but I've never tried that, and since Apps Script runs inside an iframe I'm not sure if it's possible. If I get a chance I'll play with it and update this answer, but for your own reference you could look here: create html page and print to new tab in javascript
I'm imagining something like that, except that your page an write it's html content. Something like:
var winPrint = window.open('', '_blank', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
winPrint.document.write(app.pages.TestPage.getElement().innerHTML);
winPrint.document.close();
winPrint.focus();
winPrint.print();
winPrint.close();
Hope one of those three options helps :)
So here is what I ended up doing. It isn't elegant, but it works.
I added a Print Button to a Page Fragment that pops up when a user edits a database entry.
Database Edit Button code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showDialog(app.pageFragments.FragmentName);
That Print Button goes to a different (full) Page and closes the Fragment.
Print Button Code:
app.datasources.ModelName.selectKey(widget.datasource.item._key);
app.showPage(app.pages.ModelName_Print);
app.closeDialog();
I made sure to make the new Print Page was small enough so that Chrome fits it properly into a 8.5 x 11" page (728x975).
I then created a Panel that fills the page and populated the page with Labels
#datasource.item.FieldName
I then put the following into the onDataLoad for the Panel
window.print();
So now when the user presses the Print Button in the Fragment they are taken to this new page and after the data loads they automatically get a print dialog.
The only downside is that after printing the user has to use a back button I added to return to the database page.
1.
As far as I know, you cannot combine window.open with app.pages.*, because
window.open would require url parameter at least, while app.pages.* is essentially an internal routing mechanism provided by App Maker, and it returns page object back, suitable for for switching between pages, or opening dialogs.
2.
You would probably need to style your page first, so like it includes things you would like to have printed out. To do so please use #media print
ex: We have a button on the page and would like to hide it from print page
#media print {
.app-NewPage-Button1 {
display : none;
}
}
Hope it helps.
1. Here is how it is done, in a pop up window, without messing up the current page (client script):
function print(widget, title){
var content=widget.getElement().innerHTML;
var win = window.open('', 'printWindow', 'height=600,width=800');
win.document.write('<head><title>'+title+'/title></head>');
win.document.write('<body>'+content+'</body>');
win.document.close();
win.focus();
win.print();
win.close();
}
and the onclick handler for the button is:
print(widget.root.descendants.PageFragment1, 'test');
In this example, PageFragment1 is a page fragment on the current page, hidden by adding a style with namehidden with definition .hidden{display:none;} (this is different than visible which in App Maker seems to remove the item from the DOM). Works perfectly...
2. You cannot open pages from the app in another tab. In principle something like this would do it:
var w=window.parent.parent;
w.open(w.location.protocol+'//'+w.location.host+w.location.pathname+'#PrintPage', '_blank');
But since the app is running in frame nested two deep from the launching page, and with a different origin, you will not be able to access the url that you need (the above code results in a cross origin frame access error). So you would have to hard code the URL, which changes at deployment, so it gets ugly very fast. Not that you want to anyway, the load time of an app should discourage you from wanting to do that anyway.

Return to previous page with refresh data Xamarin Forms [duplicate]

This question already has answers here:
How to pass data to the previous page using PopAsync?
(2 answers)
Closed 6 years ago.
in main page I have a button create post. When I click on it I receive editor. After input of some text I click button savePost. Then post saves to server and return to my main page, but without new post on my wall. I need to refresh that page to see my new post. How can I write code to receive my previous page with my new post on main page after clicking button savePost?
Button savePost = new Button {Text = "Save post"};
stackLayout.Children.Add(savePost);
savePost.Clicked += (sender, args) =>
{
var restService = new RestServiceImpl(UserService.User.AccessToken);
PostView post = new PostView
{
Text = textEditor.Text,
};
restService.CreatePost(post);
Navigation.PopAsync();
};
There are a few ways to go about it. The most simple one is to implement some mechanism on the OnAppearing event of the page and just reload there, or think of some way to detect a reload has to be done instead of just reloading. This can be done for instance by some bool you set to true after the 'restService.CreatePost(post);' line.
That kind of brings me to the other way. When you are using some kind of MVVM framework (have a look at FreshMvvm for example) you can execute some code when a PageModel is popped. So you have much more granular control over when to reload and detect if it is necessary at all.
A completely other way is to use the MessagingCenter. You can send out a message whenever (and from where ever) reloading is needed and let the pages which needs reloading subscribe to that and execute the reloading code whenever the right message was received.
It all depends on what your requirements and code structure is.

WebBrowser Control programming Tabs within Document pages query

I am trying to download information from a website and I have hit (yet another) brick wall in a long and tiresome journey to get something productive developed.
I have a program which uses WebBrowser to login to a site - with a valid username and password - therby allowing me to set up a legitimate connection to it and retrieve information (my own) from it.
From the initial page presented to me after login, I can use WebBrowser.Document.GetElementsByTagName("A") and WebBrowser.Document.GetElementById("Some Id") etc. to work my way around the website, and processing all the DocumentCompleted events returned until ... I arrive at a page which appears to have a TabControl embedded in it.
I need to be able to choose the middle Tab of this control, and retrieve the information it holds. When I access this information 'normally' (i.e. from IE and not from my WebBrowser program) I can click each of the three tabs and information duly appears - so its there, tantalisingly so ... but can I manupulate these Tabs from my program? I feel it should be possible, but I can't see how I can do it.
The problem manifests itself because when I am processing the page which has the Tab in it my code looks like this:
static void wb_TabPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
HtmlElement element;
element = wb.Document.GetElementById("Bills"); // Find the "Bills" tab
element.InvokeMember("Click"); // Click the "Bills" tab
// Unhook THIS routine from DocumentCompleted delivery
wb.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(wb_TabPage);
// Hook up this routine - for the next 'Document Completed' delivery - which never arrives!
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_Bills);
return;
}
And that's the problem - no more Documents are ever 'Completed' for me to process, even after the InvokeMember("Click"). It seems for all the world that the Tabs are being updated inplace, and no amount of Refresh(ing) or Navigating or Event Handling will allow me to get to a place or in a position where I can get the data from them
Does anybody have any idea how I can do this? Does anybody know how to manipulate Tabs from WebBrowser? Thanks in advance if you do ...
Try using the findcontrol function on your page. You will likely need to drill into the tab control itself to find the tab page and the controls contained in it.

Prompt to save data if and when changes have been made

I am using asp.net and I need to display a prompt to the user if they have made changes to the web page, and they accidentally close down the browser.
The page could be anything from "Edit Profile" to a "Submit a Claim" etc.
How can I can display the messagebox, ensuring that it is displayed only if changes have been made (as opposed to, the user making changes, then undo-ing the changes, and shutting down the browser)
What I have done in the past is use some client side scripting which does this check during the onbeforeunload event....
var showPrompt=true;
var isDirty=false;
var hidePopup=false;
function onBeforeUnload() {
if (showPrompt) {
if (isDirty) {
if (hidePopup || confirm("Click ok to save your changes or click cancel to discard your changes.")) {
doSave();
}
}
}
showPrompt = true;
hidePopup = false;
}
ShowPrompt can be set to false when your clicking on an anchor tag which won't navigate you away from the page. For example <a onclick='showPrompt=false' href='javascript:doX()'/>
isDirty can be used to track when you need to save something. You could for example do something like $("input").onchange(function(){isDirty=true;}); To track undo's you might want to replace isDirty with a function which checks the current state from the last saved state.
HidePopup lets us force a save without confirming to the user.
That's very difficult to even touch without understanding what's on the page. If it's a few controls you capture value at page load and store them so you can later compare. If it's a complex page you'd need to do an exact comparison to the entire viewstate.
Typically you'd handle this type of situation by setting a boolean to TRUE the first time any change is made and disregard the user changing it back. If you're just trying to avoid accidential non-save of data the user should be smart enough to know they've "undone" their changes.
You can do this with javascript. See this question and either of the first two answers.

Get the active index of the jquery accordion pane from asp.net on the server-side?

How can I get the active index of the jquery accordion pane when a button is clicked? What I want to do is when a button is clicked in pane 3 for example, I want to store that value and when the page is reloaded, I want pane 3 to remain open.
I intially had this in my server side click and when I hard code a value in for paneIndex it works fine, but obviously, I don't want to do this, I want to get the index on the click and pass that to the script.
string script = "<script type=\"text/javascript\">var paneIndex = " + 3 + "</script>";
if(!ClientScript.IsStartupScriptRegistered("JSScript"))
ClientScript.RegisterStartupScript(this.GetType(),"JSScript", script);
You could store the value in a hidden form field, and assuming you are doing a postback, that information will now be in the hidden field for you to use on the server side.
You will want to bind a function to the change event of the accordian, and store the new active index into a hidden input so that it gets sent back to the server.
As far as round-tripping the active index back to the HTML that is returned from the server - your approach is fine. Obviously instead of the hardcoded value of 3, you would put in the value from the hidden input.
$("#accordion").accordion({
active:1,
change: function(event, ui) {
var activeIndex = $("#accordion").accordion('option','active');
$("myHiddenInputId").val(activeIndex);
//alert(activeIndex);
}
});
From the server side, you can access the value and push it back to the page in a similar manner as you posted in the question:
string activeIndex = Request.Form["myHiddenInputName"];
string script = string.Format(#"<script type=""text/javascript"">var paneIndex = {0};</script>", activeIndex);
That should do it.
What's also a possibility is using the jquery.cookie plugin and storing the active pane index in a cookie. That way, everything actually happens clientside.
I don't know if this might be a valid answer, just throwing it out here for completeness sake :D

Resources