Specified cast is not valid - accessing WebBrowser in different UI thread - c#

I"m stumped on how my program is working. I'm using threading (was told to do so from another Stack Overflow answer) in order for the webBrowser2.Navigate(Url); in TestScenarios() to run asynchronously inside of the while loop in GetScenarios(). This all works fine.
Now, I added a chunk of code to inject and run some javascript inside of the WebBrowser control. However, every time I call the HtmlElement head = webBrowser2.Document.... line, I get the "Specified cast is not valid error."
I know this error has something to do with the WebBrowser control being accessed in a separate UI thread, and not being able to work that way, but I'm confused on exactly what that means and how I can fix it.
If you need more context just comment.
public void GetScenarios()
{
new Thread(() =>
{
while() {
...
TestScenarios();
}
}).Start();
}
TestScenarios() {
...
Action action = () =>
{
webBrowser2.Tag = signal;
webBrowser2.Navigate(Url);
webBrowser2.DocumentCompleted -= WebBrowserDocumentCompleted;
webBrowser2.DocumentCompleted += WebBrowserDocumentCompleted;
};
webBrowser2.Invoke(action);
signal.WaitOne();
...
//Run some javascript on the WebBrowser control
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser2.Document.InvokeScript("sayHello");
}

You are facing this problem because you are accessing the elements of webBrowser before the document is even loaded. You should move this code
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser2.Document.InvokeScript("sayHello");
To
WebBrowserDocumentCompleted
event.

First off... you should really step through it in the debugger and figure out what the object you are trying to cast is... this doesn't seem like a threading issue.
Based on your error webBrowser2.Document.GetElementsByTagName("head")[0] is not convertible to an HtmlElement.
You could also try something like this to see what the object is...
var head = webBrowser2.Document.GetElementsByTagName("head")[0] as HtmlElement;
if (head == null)
{
Console.WriteLine(typeof(head); // output the object type somehow
}

Managed to fix it by wrapping the JS scripting chunk in:
webBrowser2.Invoke(new Action(() =>
{
//......
}

Related

InvalidCastException when trying to automate WebBrowser C#

Basically I'm automating a site that has an iframe and doesn't fire DocumentComplete. I'm running a Form in an independant thread, which contains a WebBrowser. I'm trying to click search within the WebBrowser, it works normally but I'm trying to separate the Browser from the form thread-wise so I can make my code overall more procedural and implement an AutoResetEvent.
Here's the method for Clicking search:
public void ClickSearch()
{
if (search == null)
{
HtmlElementCollection links = Document.Window.Frames[0].Frames[1].Document.Links;
search = links.Cast<HtmlElement>()
.Where(x => x != null)
.FirstOrDefault(x => x.InnerText == "Search");
}
Doc.InvokeScript("htmlbSL", new object[]{search, 2, search.Id+":SEARCH", '0'});
}
Here's the code that calls it:
var evt = new AutoResetEvent(false);
HtmlElementEventHandler handler = null;
handler = new HtmlElementEventHandler(
delegate(object sender, HtmlElementEventArgs ev)
{
ev.BubbleEvent = false;
smsBrowser.Doc.Focusing -= handler;
worklist = new Worklist();
worklist.Load(smsBrowser.GetWorklistCsv());
SQLiteDatabase.InsertWorklist(worklist);
SQLiteDatabase.Commit();
SQLiteDatabase.FillWorklistGrid();
evt.Set();
});
smsBrowser.Doc.Focusing += handler;
Task.Factory.StartNew(() => smsBrowser.ClickSearch());
evt.WaitOne();
The line:
HtmlElementCollection links = Document.Window.Frames[0].Frames[1].Document.Links;
is giving me an InvalidCastException. Also, any advice as to how to best do this would be much appreciated, I want to avoid Application.DoEvents(), I also want it to be more procedure (I have many events attaching and detaching). The calling method is also running within an event handler, I'd like to put them within the same method with implemented waits to clean up my code.
I followed this guide earlier: http://www.albahari.com/threading/part2.aspx.
Here are the exception details, though they don't provide much help.
An exception of type 'System.InvalidCastException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: Specified cast is not valid.

Supress the "are you sure you want to leave this page" popup in the .NET webbrowser control

I have a web browser automation project written in WinForms C#.
During the navigation there is a point where the browser does the "are you sure you want to leave this page?" popup.
We need this popup, so I cannot remove it from the website code, which means I have to override it in my automation app.
Does anyone have an idea how to do this?
and here was the smooth solution..
add a reference to mshtml and add using mshtml;
Browser.Navigated +=
new WebBrowserNavigatedEventHandler(
(object sender, WebBrowserNavigatedEventArgs args) => {
Action<HtmlDocument> blockAlerts = (HtmlDocument d) => {
HtmlElement h = d.GetElementsByTagName("head")[0];
HtmlElement s = d.CreateElement("script");
IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;
e.text = "window.alert=function(){};";
h.AppendChild(s);
};
WebBrowser b = sender as WebBrowser;
blockAlerts(b.Document);
for (int i = 0; i < b.Document.Window.Frames.Count; i++)
try { blockAlerts(b.Document.Window.Frames[i].Document); }
catch (Exception) { };
}
);
Are you able to make any changes to the website code?
If so, you might look at exposing an object through ObjectForScripting, then having the website code check window.external (and possibly interrogating your object) before it decides to display the popup - so if it can't find your object, it assumes it's being used normally and shows it.
Don't need add anymore. Try it. Work like a charm. ^_^
private void webNavigated(object sender, WebBrowserNavigatedEventArgs e)
{
HtmlDocument doc = webBrowser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text", "function cancelOut() { window.onbeforeunload = null; window.alert = function () { }; window.confirm=function () { }}");
head.AppendChild(s);
webBrowser.Document.InvokeScript("cancelOut");
}

WebBrowser.Document.Body is always null

I have a WebBrowser document set to be in edit mode. I am trying to manipulate the inner text of the body element by using WebBrowser.Document.Body.InnerText, however, WebBrowser.Document.Body remains null.
Here is the code where I create the document contents:
private WebBrowser HtmlEditor = new WebBrowser();
public HtmlEditControl()
{
InitializeComponent();
HtmlEditor.DocumentText = "<html><body></body></html>";
myDoc = (IHTMLDocument2)HtmlEditor.Document.DomDocument;
myDoc.designMode = "On";
HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
myContentsChanged = false;
}
I can edit code and everything fine, but I don't understand why HtmlEditor.Document.Body remains null. I know I could always just reset the document body whenever I need to load text into the form, but I would prefer to understand why this is behaving the way it is, if nothing else then for the knowledge.
Any help on this is greatly appreciated.
You have to wait for the Web Browser's DocumentCompleted event to fire for the DomDocument.Body to not be null. I just tested this to verify. I suppose the question still remains: how are you able to edit through the underlying COM interface when the document has not completely loaded?
I checked to see if the IHTMLDocument2 pointers were the same in DocumentCompleted and the constructor. They are, which might indicate that the underlying COM object reuses a single HTML document object. It seems like any changes you make in the constructor at least have a pretty good chance of getting overwritten or throwing an exception.
For example, if I do this in the constructor, I get an error:
IHTMLDocument2 p1 = (IHTMLDocument2) HTMLEditor.Document.DomDocument;
p1.title = "Hello world!";
If I do the same in a DocumentCompleted handler, it works fine.
Hope this helps. Thanks.
Use DocumentCompleted event first, it occurs when the WebBrowser control finishes loading a document:
public HtmlEditControl()
{
InitializeComponent();
HtmlEditor.DocumentText = "<html><body></body></html>";
HtmlEditor.DocumentCompleted += HtmlEditorDocumentCompleted;
}
void HtmlEditorDocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
myDoc = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
myDoc.designMode = "On";
HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
myContentsChanged = false;
}
or simple way:
public HtmlEditControl()
{
InitializeComponent();
HtmlEditor.DocumentText = "<html><body></body></html>";
HtmlEditor.DocumentCompleted += (sender, e) =>
{
myDoc = (IHTMLDocument2) HtmlEditor.Document.DomDocument;
myDoc.designMode = "On";
HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
myContentsChanged = false;
};
}
You need to let the WebBrowser control to work alone a bit to give it some time to set the Document.Body property.
I do that by calling Application.DoEvents();.
For instance in your code:
private WebBrowser HtmlEditor = new WebBrowser();
public HtmlEditControl()
{
InitializeComponent();
HtmlEditor.DocumentText = "<html><body></body></html>";
// Let's leave the WebBrowser control working alone.
while (HtmlEditor.Document.Body == null)
{
Application.DoEvents();
}
myDoc = (IHTMLDocument2)HtmlEditor.Document.DomDocument;
myDoc.designMode = "On";
HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
myContentsChanged = false;
}
if (HtmlEditor.Document.Body == null)
{
HtmlEditor.Document.OpenNew(false).Write(#"<html><body><div id=""editable""></div></body></html>");
}
HtmlEditor.Document.Body.SetAttribute("contentEditable", "true");

Inject JavaScript with jQuery at runtime into WebBrowser

I have desktop application with WebBrowser control and try to inject JavaScript into loaded page.
For this I added two script elements:
private static void AddJQueryElement(HtmlElement head)
{
HtmlElement scriptEl = head.Document.CreateElement("script");
IHTMLScriptElement jQueryElement = (IHTMLScriptElement)scriptEl.DomElement;
jQueryElement.src = #"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head.AppendChild(scriptEl);
}
private static void AddScriptElement(HtmlElement head)
{
HtmlElement scriptEl = head.Document.CreateElement("script");
IHTMLScriptElement myScriptElement = (IHTMLScriptElement)scriptEl.DomElement;
myScriptElement.src = #"file:///c:\JScript.js";
head.AppendChild(scriptEl);
}
how you can see first is reference to jQuery because I use it in my script. When I try to invoke function from my script using _webBrowser.Document.InvokeScript WebBrowser throws
Script Error :"Object expected". and points to the line where i try to use jQuery (var tags = $("Body").find("*");).
How can I prevent this error?
Another interesting thing: if I add something like alert("hello"); to start of my function all works fine.
Haven't got correct answer, but have solved the problem by using local copy of jquery.min.js.
It's possible you aren't specifying your script to run on load. alert("hello") is buying that time needed to download the script/finish building the HTML.
$(document).ready(function() {
// Handler for .ready() called.
});

A Possible Threading/COM/UI problem

I am writing a toolbar for IE(6+). I have used the various sample bars from
codeproject.com (http://www.codeproject.com/KB/dotnet/IE_toolbar.aspx), and have a toolbar that works, registers unregisters etc. What I want the toolbar to do is to highlight divs within an html page as the users' mouse moves over that div. So far the highlighting code works, but I would like to display the name of the div (if it exists) in a label on the toolbar (changing as the mouse moves etc).
I cannot for the life of me get this to happen and trying to debug it is a nightmare. As the assembly is hosted in IE, I suspect that I am causing an exception (in IE) by trying to update the text on the label from a thread that didn't create that control, but because that exception is happening in IE, I don't see it.
Is the solution to try to update the control in a thread-safe way using Invoke? If so how?
Here is the event code:
private void Explorer_MouseOverEvent(mshtml.IHTMLEventObj e)
{
mshtml.IHTMLDocument2 doc = this.Explorer.Document as IHTMLDocument2;
element = doc.elementFromPoint(e.clientX, e.clientY);
if (element.tagName.Equals("DIV", StringComparison.InvariantCultureIgnoreCase))
{
element.style.border = "thin solid blue;";
if (element.className != null)
{
UpdateToolstrip(element.className);
}
}
e.returnValue = false;
}
and here is an attempt at thread-safe update of the toolbar:
delegate void UpdateToolstripDelegate(string text);
public void UpdateToolstrip(string text)
{
if (this.toolStripLabel1.InvokeRequired == false)
{
this.toolStripLabel1.Text = text;
}
else
{
this.Invoke(new UpdateToolstripDelegate(UpdateToolstrip), new object[] { text });
}
}
Any suggestions much appreciated.
I can't really reproduce the issue (creating a test project for an IE toolbar is a tad too much work), but you can try this:
Add the following routine to a public static (extensions methods) class:
public static void Invoke(this Control control, MethodInvoker methodInvoker)
{
if (control.InvokeRequired)
control.Invoke(methodInvoker);
else
methodInvoker();
}
And then replace the section of similar code in the first block with this:
if (element.className != null)
{
this.Invoke(() => toolStripLabel1.Text = element.className);
}
This is a sure-fire way of avoiding thread-safe issues in UI applications.

Categories

Resources