Capture Javascript variables from webbrowser control

I have an app written in VB6 which controls a third party web app. What I am trying to do is capture the contents of a dropdown list box which is populated by a javascript function. Can anyone advise  how to capture this information in VB?
This is proving difficult, hence the points value.
Who is Participating?
AzraSoundConnect With a Mentor Commented:
That looks right to me.  Using selectedIndex will select an item, but I think I have seen it where it does not fire the onclick/onchange event thus not firing the javascript function, so calling the Click method will trigger it, allowing you to move on to the next select element.  Good job!
What you can do is use the .document.body.innerhtml command to get the HTML and then exract each value. I think there is a way even if you know the form a drop down box's name to get each item value, I am not sure how to do it however.

third party web app?

can u provide more info on the same.

as in, if this were jus an IE window, it would be pretty straightfwd.

lets assume that was IE.

we do an:

set obj = getobject(,<class name for IE>)

obj.document.form[0]. get to the 'select' tag....

and we can read out the same by traversing along the document object.

more info plz.
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

appariConnect With a Mentor Commented:
using webbrowser control first navigate to the page you want.

webbrowser1.navigate2("webpage address..")

after loading the page is completed you can get all the script blocks as follows.

'WebBrowser1.document.scripts.length    returns the nummber of script blocks found in the document
msgbox WebBrowser1.document.scripts.length

for i=0 to WebBrowser1.document.scripts.length -1
       debug.print WebBrowser1.document.scripts(i).src    ' in case script is from external script file this gets the name of the script file.
       debug.print WebBrowser1.document.scripts(i).text
next i

now you can store the script blocks in string variables and process them as you per your requirement.
AzraSoundConnect With a Mentor Commented:
I think you should be able to do something like this:

'assume the dropdown element looks like this in the html
<select name="dropDownBox">
    <option value="1">Blah</option>

Dim o As Object

For Each o In WebBrowser.Document.all("dropDownBox").options
    MsgBox o.value
TrevorParnhamntlAuthor Commented:
Thanks to everyone for their answers. Unfortunately, I could not get any of them to work correctly.
appari came closest, but this method did not list all the scripts. I think this may be due to a large amount of comments in the source code.

here is an example:

<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="../stylesheet/default.css">
<style>SELECT {behavior:url(../htc/}</style>

<!-- server vbscript -->

<!-- client vbscript -->
<script LANGUAGE="vbscript" src="../common/vbscript/otm_helper.vbi"></script>
<script language="vbscript" src="../common/vbscript/encode.vbi"></script>
<script language="vbscript" src="../worknotes/worknotes.vbi"></script>
<script language="vbscript" src="../res/worknotes/worknotes_res.vbi"></script>
<script language="vbscript" src="../common/vbscript/common.vbi"></script>

<!-- client javascript -->
<script language="javascript" src="../common/javascript/cache.js"></script>
<script language="javascript" src="../common/javascript/timer.js"></script>
<script language="javascript" src="../common/javascript/cached_data.js"></script>
<script language="javascript" src="../common/javascript/datetime.js"></script>

Azrasound's suggestion probably should have worked but because the population of the dropdown is dependant on another javascript function which populates another dropdown, I kept getting 'object with block variable not set' error, when I tried to run this code.

However, I have managed to solve the problem. Fyi, this is how I did it.


       For i = 0 To WebBrowser1.Document.frames.length - 1
           Debug.Print WebBrowser1.Document.frames.Name
             For Each HTMLTag In WebBrowser1.Document.frames(i).Document.All
                       Select Case HTMLTag.tagName
                           Case "SELECT"
                                    If HTMLTag.getAttribute("name") = "selCode1" Then 'this is the name of the dropdown
                                            For v = 0 To HTMLTag.children.length - 1
                                                    Debug.Print HTMLTag.children(v).Text
                                    End If
                        End Select

As all contributors have added to my knowledge and stimulated my brain, I am inclined to split the points, even though I actually answered the question myself.
I would appreciate your comments.

At what point is the dropdown filled and how does it relate to the time at which you attempt to grab the info from that dropdown?
TrevorParnhamntlAuthor Commented:
There are several dropdowns and each is filled based on the selection from the previous one.
My app is selecting from the dropdown depending on variable within my app. E.g. the use selects from a list in my app and this is linked to a corresponding item in the web page dropdown. It looks for the item in the dropdown and then selects it. The java function in the webpage then populates the next dropdown based on this value and the process repeats using another variable from my app.

This is how I got it to work, not exactly pretty but it works and is fast:

For i = 0 To WebBrowser1.Document.frames.length - 1
     For Each HTMLTag In WebBrowser1.Document.frames(i).Document.All ' Locate the correct frame

        Select Case HTMLTag.tagName
           Case "SELECT"                      
                 If HTMLTag.getAttribute("name") = "selCode1" Then    'locate the first dropdown
                     For v = 0 To HTMLTag.children.length - 1
                        If Trim(HTMLTag.children(v).Text) = Trim(majReason) Then 'look for match with app variable
                            HTMLTag.selectedIndex = v         'next three lines select and populate the web app dropdown
                            HTMLTag.Click                            ' the web app then runs the java function for the next dropdown
                            HTMLTag.selectedIndex = v
                           Exit For                                       ' then exit
                         End If  
                  End If

                 If HTMLTag.getAttribute("name") = "selCode2" Then     'repeat the process for the next dropdown
                     For v = 0 To HTMLTag.children.length - 1
                       If Trim(HTMLTag.children(v).Text) = Trim(callreason) Then
                           HTMLTag.selectedIndex = v
                           HTMLTag.selectedIndex = v
                         Exit For
                       End If
          End Select
Next i

This then carries on until all four dropdowns have been populated.

many thanks

TrevorParnhamntlAuthor Commented:
In order to be able to award points can I expand my original question?

I still cannot access all javascript variables I am able to find some of the scripts, but not all and this doesn't give me access to the variables or values returned.
Although I have solved my initial problem with the drop down lists, I have other routines to write where I need to access actrual variables from javascript (or VB)functions, particularly hidden values.

Hope I have made this clear.


Hidden values?  What do you mean by that?  Not hidden input elements correct (e.g., <input type="hidden" value="something">)?

As far as actual javascript variables, I never found a way to do that.  However, to access and call the functions, I believe the syntax was something like:

There's a cheap way of getting variables.. ExecScript has access to the values of variables so you can pass a custom javascript function to place the value of the variable at a place you can read it. For me, I just opened a new window with the location being the variable (about:blank to avoid error page).. handled the page in a WebBrowser2 and viewed it's source.. it's rough but a method of doing such. Alternatively.. you could try a javascript function that changes the status/title and then read the status/title using WebBrowser1 interface..

Private Sub Command1_Click()
    WebBrowser1.Document.parentWindow.execScript "'about:'+Test3);"
End Sub
Private Sub Form_Load()
    WebBrowser1.StatusBar = True
    WebBrowser1.Navigate "c:\test.html"
End Sub
Private Sub WebBrowser1_NewWindow2(ppDisp As Object, Cancel As Boolean)
    Set ppDisp = WebBrowser2.Object
End Sub
Private Sub WebBrowser2_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    MsgBox "Your variable's value is: " & WebBrowser2.Document.body.outerText
End Sub

"test.html" includes...

var Test1='StringTest1';
var Test2=Test1;
var Test3=Test2;
Meh.. after thinking of using the title in the previous post.. it works fine also..

Private Sub Command1_Click()
    WebBrowser1.Document.parentWindow.execScript "document.title=Test3;"
    MsgBox WebBrowser1.Document.Title '<-- var Test3's value
End Sub
TrevorParnhamntlAuthor Commented:
Apologies for not getting back to you.
Can we leave this open for a while longer as I am involved in another project at the moment, although I still haven't solved this problem.

Sorry for any inconvenience.
'This is short code that will add a javascript to a webpage as it loads in your browser
' In this particular example my script adds a javascript that will send the value of tagVars variable to the clibboard and then
'have a textbox(make sure its multiline) get the data from the clipboard

'all code goes in the webbrowser1_DocumentComplete event
Private Sub webbrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)

'Just avioding errors
On Error Resume Next

'Clear the textbox and clipboard.
    txtData.Text = ""
    WebBrowser1.Document.expando = True ' Not sure if required but can't hurt

' The following line add a link to the page that when clicked, runs a javascript from its href
    WebBrowser1.Document.body.insertBefore (WebBrowser1.Document.createElement("<a name=""see"" href=""javascript:if(typeof(tagVars)!='undefined') var sucsess = window.clipboardData.setData('Text',tagVars);"" >test2</a>"))

' This line clicks the link and runs the javascript
    WebBrowser1.Document.links(WebBrowser1.Document.links.length - 1).Click
'This loops makes sure the javascript has run before proceeding
    Loop While WebBrowser1.Busy
' Set focus to the text box and then paste
    txtData.SelText = Clipboard.GetText(vbCFText)
End Sub

'Note adding the javascript is tricky and you may have to view the output of createElement in the debuger to see where it
'goes wrong
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.