I'm writing an application that uses the WebBrowser control to view web content that can change with AJAX that adds new content/elements. I can't seem to get at the new elements any way I've tried. BrowserCtl.DocumentText doesn't have the up-to-date page and of course it's not in "view source" either.
Is there some way to get this new data using this control? :( Please help. Thanks!
IE:
Browser.Navigate("www.somewebpagewithAJAX.com");
//Code that waits for browser to finish...
...
//WebBrowser control has loaded content and AJAX has loaded new content
// (is visible at runtime on form) but can't see them in Browser.Document.All
// or Browser.DocumentText :(
I solved the problem for me.
the key is, attaching a handler for onPropertyChanged
event of the div element which is being populated via ajax call.
HtmlElement target = webBrowser.Document.GetElementById("div_populated_by_ajax");
if (target != null)
{
target.AttachEventHandler("onpropertychange", handler);
}
and finally,
private void handler(Object sender, EventArgs e)
{
HtmlElement div = webBrowser.Document.GetElementById("div_populated_by_ajax");
if (div == null) return;
String contentLoaded = div.InnerHtml; // get the content loaded via ajax
}
using System;
using System.Windows.Forms;
namespace WebBrowserDemo
{
class Program
{
public const string TestUrl = "http://www.w3schools.com/Ajax/tryit_view.asp?filename=tryajax_first";
[STAThread]
static void Main(string[] args)
{
WebBrowser wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(TestUrl);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey(true);
}
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
HtmlElement document = wb.Document.GetElementsByTagName("html")[0];
HtmlElement button = wb.Document.GetElementsByTagName("button")[0];
Console.WriteLine(document.OuterHtml + "\n");
button.InvokeMember("Click");
Console.WriteLine(document.OuterHtml);
}
}
}
You will need to use DOM for it. Cast WebBrowser.Document.DomDocument to IHTMLDocument?. You will have to import some COM interfaces or Microsoft.mshtml assembly.
Have a look to http://msdn.microsoft.com/en-us/library/aa752641(VS.85).aspx for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With