我想注入一个javascript,以便将焦点设置到第一个输入框。
我目前的代码是:
Me.WebBrowser1.Focus()
Dim i&
Dim JS(100) As String
'The following Javascript-injection ensures, that the first
'found input-element (if there is one) will be focused
' i = i + 1 : JS(i) = "<script>"
i = i + 1 : JS(i) = "var inputElements = document.getElementsByTagName('input');"
i = i + 1 : JS(i) = "for(i=0; i<inputElements.length; i++)"
i = i + 1 : JS(i) = "{"
i = i + 1 : JS(i) = " if (inputElements[i].type != 'hidden')"
i = i + 1 : JS(i) = " {"
i = i + 1 : JS(i) = " if (inputElements[i].disabled == false)"
i = i + 1 : JS(i) = " {"
' If uSetFocusToFirstBox Then
i = i + 1 : JS(i) = " inputElements[i].focus();"
' End If
'If uScrollIntoView Then
i = i + 1 : JS(i) = " inputElements[i].scrollIntoView(true);"
'End If
i = i + 1 : JS(i) = " break;"
i = i + 1 : JS(i) = " }"
i = i + 1 : JS(i) = " }"
i = i + 1 : JS(i) = "}"
Dim head As HtmlElement = Me.WebBrowser1.Document.GetElementsByTagName("head")(0)
Dim scriptEl As HtmlElement = Me.WebBrowser1.Document.CreateElement("script")
Dim element As IHTMLScriptElement = DirectCast(scriptEl.DomElement, IHTMLScriptElement)
element.text = Join(JS, "")
head.AppendChild(scriptEl)
Me.WebBrowser1.Document.InvokeScript("sayHello")
有人看到我的错误吗?
谢谢!
答案 0 :(得分:1)
选项1 - 无脚本
您无需将脚本注入文档。你可以处理DocumentCompleted
事件,然后使用GetElementByTagName
找到输入元素并找到第一个带有type="text"
的输入,然后调用Focus()
,它也会自动滚动焦点输入到视图:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
Dim firstTextBox = Me.WebBrowser1.Document.GetElementsByTagName("input") _
.Cast(Of HtmlElement)() _
.Where(Function(element)
Return element.GetAttribute("type") = "text" And _
element.Enabled = True
End Function) _
.FirstOrDefault()
If (firstTextBox IsNot Nothing) Then
firstTextBox.Focus()
End If
End Sub
选项2 - 注入脚本
出于这个原因你不需要使用脚本,但只是为了你需要注入脚本的情况,这里有一个例子。您应该向项目添加对Microsoft.mshtml
的引用并编写此类代码:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
Dim scriptText = "var inputElements = document.getElementsByTagName('input');" & _
"for(i=0; i<inputElements.length; i++){" & _
" if (inputElements[i].type == 'text' && !inputElements[i].disabled){" & _
" inputElements[i].focus();" & _
" inputElements[i].scrollIntoView(true);" & _
" break;" & _
" }" & _
"}"
Dim head As HtmlElement = Me.WebBrowser1.Document.GetElementsByTagName("head")(0)
Dim script As HtmlElement = Me.WebBrowser1.Document.CreateElement("script")
Dim scriptElement As IHTMLScriptElement = DirectCast(script.DomElement, IHTMLScriptElement)
scriptElement.text = scriptText
head.AppendChild(script)
End Sub