How to retrive form value using execScript in VB6?

2019-07-18 21:18发布

问题:

Say, this is my code

Dim Address as string

WebBrowser1.Document.parentWindow.execScript("var a = document.form1.address.text", "JavaScript")

how can i extract the value of document.form1.address.text to my VB6 variable Address?

回答1:

You can use DOM.

Let us say we have simple HTML form:

<html>
<body>
    <form name="form1">
        Address: <input type="text" id="address">
    </form> 
</body>
</html>

After loading it in a WebBrowser control and making sure DOM is ready, we can get text of address field in the following way:

Private Sub cmdGetAddressText_Click()
    Dim HTMLElement As Object
    Dim Address As String

    Set HTMLElement = WebBrowser1.Document.GetElementByID("address")
    Address = HTMLElement.Value

    MsgBox Address
End Sub

Edit:

It's even simpler than that. You can access field value directly from VB6:

Address = WebBrowser1.Document.Form1.Address.Value

Edit#2

It is also possible to get a value of a JavaScript variable if you wish to do so:

Private Sub cmdJSVar_Click()
    Dim Address As String
    Call WebBrowser1.Document.parentWindow.execScript("var a=document.form1.address.value; alert(a);")
    Address = WebBrowser1.Document.Script.a

    MsgBox Address
End Sub

Notice that JS variable name in .Script.a is case-sensitive (i.e. .Script.A won't work). It took some time to figure this out.



回答2:

You can provide an IDispatch implementation to window.external but this is not easy to do VB6.

Easier would be to use location in JS to navigate to an address that you can capture in Navigate event in VB6 e.g. http://callback?param=value&param2=anothervalue, detect "callback" host, parse the parameters and cancel navigation.



标签: vb6