Windows Form Application – Manipulating input-elements in WinForm WebBrowser
Although I am familiar with HttpWebResponse/HttpWebRequest to login to a website, I was trying it now via using the mshtml library and found some weird behavior and I would like to see if someone else might be able to help me out here..
I have an HTML login page with a java backend with a Username field, a Password field and a Button.
The logic is very basic, I have a built a winform app with a built in webbrowser.
At the Document_Completed event I use the following code to enter my settings and to click the button.
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser.Url.ToString() == #"MyWebPage/signin")
{
HTMLDocument hdc = new HTMLDocumentClass();
hdc = (HTMLDocument)webBrowser.Document.DomDocument;
IHTMLElement elb = hdc.getElementById("login_button");
IHTMLInputElement elu = (IHTMLInputElement)hdc.getElementById("username");
IHTMLInputElement elp = (IHTMLInputElement)hdc.getElementById("password");
try
{
elu.value = "MyID";
elp.value = "MyPwd";
elb.click();
}
catch { }
}
}
Apart for this code being very quick and without error handling, it should do the trick and it does, partially..
There are two scenario's:
I launch the tool, it loads the webpage.
The tool populates the UserID field and the Password field correctly
The tool fails to click the button
I click the button manually, I am logged in, I click logout, I am back at login page
I immediatly logged in again, the tool enters the information
The tool immediatly clicks the button as well.
Is there anyone who might be able to explain me why this happens and how I could get around this with the current setup (hence not using HttpWebRequest). I don't see the difference between loading the page at startup or being redirected after logout, but apparently there is a difference in there or I am doing something wrong.
Any feedback on this matter is very much appreciated.
Thanks,
Kevin
EDIT:
I added a Button to my Windows Form that bas the same backend Code as below in order to click the button on the webpage, this works perfectly.
I triggered clicking this button in the webBrowser_Completed event but it doesn't work.
For some reason, everything I add to the webBrowser_DocumentCompleted event does not allow me to trigger the click event for the button in my WebBrowser control. Once that entire event has completed, if I then try to trigger it it works but I would like to automate this.. Any advice?
This might be a long shot and not the most elegant workaround but how about letting a backgroundworker run for a second in your DocumentCompleted event that then triggers the button that you clicked from it's seperate thread. This might just get this automated.
As this will run from a different thread, keep in mind that you might have to invoke certain controls so this might be another downside to this workaround..
If this doesn't work then, as Regfor previously suggested, Watin.org can help you out.
how about this :
HtmlElement button = webBrowser.HtmlDocument.GetElementById("login_button");
button.InvokeMember("click");
it works in my program.
Related
I'm trying to do web automation by creating a Windows Form application in C# using WebBrowser. I currently have the code below that navigates to Youtube and inputs a string in Youtube's search bar.
website.Navigate("www.youtube.com");
website.Document.GetElementById("search").InnerText = "Cavaliers vs Boston highlights";
However, I get a NullReferenceException in the line
website.Document.GetElementById("search").InnerText = "Cavaliers vs Boston highlights";
I tried searching in different websites on how a WebBrowser is able to determine if it has completely finished loading the website you have specified in the Navigate method but so far I haven't found any.
What I have found online are methods that checks a WebBrowser's ready state but upon trying it, it doesn't even load the Form I created, yet still proceeds to the GetElementById method.
Hoping someone can help me with this, been trying to find a solution since morning.
Try to add an event listener to WebBrowser. The WebBrowser has a WebBrowser.DocumentCompleted event that occurs when the web page has been fully loaded.
Something like
public frmMain()
{
website.DocumentCompleted += website_DocumentCompleted;
}
public void website_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
website.Document.GetElementById("search").InnerText = "Cavaliers vs Boston highlights"
}
where frmMain is your form. It could be of course added in somewhere else too.
i am facing an issue in winform app, i am using webbrowser control. At one point i am using for loop and in the loop i have to invoke the Enter button event programatically. It is something like below:
for (int i = 1; i <= 4; i++)
{
htmlElement = webBrowser1.Document.GetElementById(PagerTxtBoxID);
htmlElement.InnerText = i.ToString();
SendKeys.Send("{ENTER}");
}
now every time at SendKeys.Send("{ENTER}"); the page should gets refreshed with new values (inside webbrowser control).
However it is not working and the page is not refreshing and when i am trying ti debug, it shows changes are not allowed while code is running.
Requesting you folks to please guide me from here.
SendKeys.Send(...) actually send the keyboard signals as when you are hitting keys on whatever is focused now. If you are on debug, it probably tries to send enter key to visual studio, modifying the C# code. You have to figure out another way of interacting with the webbrowser. One method is to programatically click a html button.
I will try my best to express what I do not understand about WebForms. Maybe somone can explain it to me....
I work in 'quite big' WebForms (website) Application.
Application already has a PopUp (which I HAVE TO USE, because I dont have time to make a new one) like MessageBox in Winforms, but:
it's place is in MasterPage.master (I use it like ((MasterPage)Poup.Show("blablabla", yes_no));
I can add buttons to it and change style etc.
it doenst stop application (like .ShowDialog() in WinForms), so I have to assign onClick events dynamicly and assign/catch them on Page_Load to go to the wanted method depending on users input on form. At the moment i can't to anything about it.
And here is the problem:
Depending on form validation, if users press a button (on a form) - then form realods it's TextBox.Text's values and changes DropDownLists's SelectedIndexes and SelectedValues.
BUT IF YOU GO TO THE SAME METHOD WITH MY POPUP WINDOW:
ex: Do you confirm? YES/NO
If you press You press ANY button, then: CHANGES ARE VISIBLE BY CODEBEHIND BUT TEXTBOXES ARE STILL VISIBLE WITH PREVIOUS DATA ON THE SCREEN, ALSO DROPDOWNLISTS HAVE OLD VALUES SELECTED
BUT IF YOU PRESS A FORM BUTTON (WHATEVER WHICH), EVEN IF IT'S METHOD DOES NOTHING - ALL FORM WILL "RELOAD" AND HAVE PROPER DATA ON THE SCREEN.
(it's not about Runat="server" or AutoPostBack, I checked it)
I dont event know what to do about it :(
Update panels are used to partial refresh of some fields inside him, caused by certain triggers, like buttons, textchanged, etc.
See more about update panel's:
https://msdn.microsoft.com/en-us/library/bb399001.aspx
http://www.asp.net/web-forms/overview/older-versions-getting-started/aspnet-ajax/understanding-asp-net-ajax-updatepanel-triggers
http://www.asp.net/ajax/documentation/live/tutorials/IntroductionUpdatePanel.aspx
(Haven't worked with web forms events in a while, just answering in case nobody else does.)
Out of curiosity, what happens if, in your javascript handler for your popop button, you getElementById one of the form buttons on the main page and call ".click()" on it?
The basic problem sounds like there's a runat/server form on the main page, with certain behaviors associated with it, which is submitted by the main page runat server buttons but not by your popup JS.
Easy enough to test with the above approach. If that works, take a step further and try to figure out why it worked, based on what those buttons are doing.
(If you're not using JS at all for the popup, then View Source the output HTML, because I'm sure it is. Backtracking those calls should help you understand the trace from popup button press to form submission.)
I probably mislead you by "OnClick", it's NOT javascript OnClick="method()" issue.
I mean ClickEvent on a button (in codebehind). For Ex. If form is validated I have to do:
ViewState["PopUpSelection"] = "yes_no";
(MasterPage)PopUp.Show("blabla",yes_no) //loads popup from MasterPage;
return;
then on Page_Load I have:
**if (string)ViewState["PopUpSelection"] == "yes_no"
{
ButtonConfirmYes.Click += new EventHandler(MyMethod);
}**
And if method "MyMethod" is called from a FORM button, everything "will go ok".
If you call the same method from PopUp button: changes are visible by codebehind, but on the screen nothing happens, unless i press ANY FORM BUTTON, whatever it does
I know that the dialog(showMessage) is a closed API and that you can not force a click event on Dialog with any web-based technologies such as jQuery or Javascript. The instance of the window within the browser is single threaded and locks the thread until the dialog receives an event. This I understand.
What I am trying to do is simulate a click event pragmatically for Test Case purposes. I am using the Telerik testing framework to run these Test Cases in C# .NET 4.5 environment.
So is it possible to simulate this click event? It is testing the behavior of one our buttons that when clicked the user must confirm they are leaving the page without saving changes.
Thanks to all in advance!
I am not familiar with Telerik's testing tools, but as far as i know the only way to "issue" such a click would be with a ui macro that automated mouse motions and actually clicked the screen at a particular location.
That said, you may be able to solve your problem by using a mocked method. Rather than directly calling window.prompt, instead define your own prompt function along the lines of:
debug = true; //remove or set to false when not testing
var myPrompt = function(){
if(debug){
return "Greetings, Program";
} else {
return prompt("Please enter your greeting:","Greeting");
}
}
You can naturally set this up for other types of message box, so long as you keep the type they return in mind.
I have created a little Win Form App in C# and added the WebBrowser component to it. What i am trying to achieve is a little app that can load a local html page from a file which has "custom" protocols in it and can of course also navigate to a web address.
For example i would have entry as follows in my webpage
'Close Company</TD></TR>' which would open a task in a program.
The way i tried to achieve this was via the Navigating event as shown below
private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if ((webBrowser.StatusText.Contains("Special")))
{
//For some reason the stop doesn't do much it still tries to proceed to special:123
//diplaying can not load page..
webBrowser.Stop();
//Launch program here.
MessageBox.Show("Special Command Found");
}
}
Problem is that it still navigates and says it can't find of course the page.
I swapped Stop with GoBack which for some reason has the same issue the first time i run it and when i then select backward in the browser it works from thereon.
I also tried navigated and use of GoBack, besides having a flashing in the app from going back the event does not fire again after the first time anymore.
Has anyone any ideas how to solve this or what i am doing wrong here ?
Instead of using WebBrowser.Stop();
just set e.cancel = true;