Weird error when calling document.GetElementsByTagName(“head”)

社会主义新天地 提交于 2019-12-23 01:43:21

问题


I have an application that uses 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.


回答1:


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
}


来源:https://stackoverflow.com/questions/5321235/weird-error-when-calling-document-getelementsbytagnamehead

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!