开发者

Weird error when calling document.GetElementsByTagName("head")

I have an application that u开发者_开发知识库ses the following code to inject JavaScript in a web page in a WebBrowser:

HtmlElement head = document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = document.CreateElement("script"); 
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement; 
element.text = CurrentFuncs; 
head.AppendChild(scriptEl); 

But I just got an error report from a customer that got an exception in the document.GetElementsByTagName("head")[0] piece of code that says: "Value of '0' is not valid for 'index'. 'index' should be between 0 and -1." I'm pretty sure that's from the [0] thing in that line of code, but no idea why.

I assume is because there is no "head" element. I just uploaded a page with no head and opened it with my application, but the error didn't reproduce. The WebBrowser automatically adds the "head" element. I even tried uploading a ".txt" file and still no error. Any idea why could this be happening or how could I reproduce the error?

Unfortunately I don't know on which web page the error occurred.


I suspect your code looks like this:

string url = "http://www.google.com";
webBrowser1.Navigate(url);
HtmlDocument document = webBrowser1.Document;
HtmlElement head = document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = document.CreateElement("script");
mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)scriptEl.DomElement;
element.text = "alert('1');";
head.AppendChild(scriptEl);

The problem is that straight after Navigate, the document isn't loaded yet. You will need to move the part of the code that access the document into the DocumentCompleted handler.

private void Go()
{
    webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    string url = "http://www.google.com";
    webBrowser1.Navigate(url);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    HtmlDocument document = webBrowser1.Document;
    HtmlElement head = document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = document.CreateElement("script");
    mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)scriptEl.DomElement;
    element.text = "alert('1');";
    head.AppendChild(scriptEl);
    // Code here
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜