Solved

Capture Javascript variables from webbrowser control

Posted on 2004-04-02
16
8,754 Views
Last Modified: 2012-05-04
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.
0
Comment
Question by:TrevorParnhamntl
  • 4
  • 4
  • 2
  • +4
16 Comments
 
LVL 19

Expert Comment

by:BrianGEFF719
Comment Utility
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.


-Brian
0
 
LVL 7

Expert Comment

by:_agj_
Comment Utility
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]. etc...to get to the 'select' tag....

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

more info plz.
0
 
LVL 39

Assisted Solution

by:appari
appari earned 200 total points
Comment Utility
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.
0
 
LVL 28

Assisted Solution

by:AzraSound
AzraSound earned 300 total points
Comment Utility
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>
     ...etc
</select>


Dim o As Object

For Each o In WebBrowser.Document.all("dropDownBox").options
    MsgBox o.value
Next
0
 
LVL 1

Author Comment

by:TrevorParnhamntl
Comment Utility
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/Select.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.

Dim HTMLTag As MSHTML.HTMLBaseElement

       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
                                            Next
                                    End If
                        End Select
              Next
      Next

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.

0
 
LVL 28

Expert Comment

by:AzraSound
Comment Utility
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?
0
 
LVL 1

Author Comment

by:TrevorParnhamntl
Comment Utility
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  
                      Next
                  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.Click
                           HTMLTag.selectedIndex = v
                         Exit For
                       End If
                     Next
          End Select
   Next
Next i

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

many thanks

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 28

Accepted Solution

by:
AzraSound earned 300 total points
Comment Utility
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!
0
 
LVL 1

Author Comment

by:TrevorParnhamntl
Comment Utility
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.

Regards,

Trevor
0
 
LVL 28

Expert Comment

by:AzraSound
Comment Utility
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:


Browser.Document.parentWindow.execScript("nameOfJavascriptFunction")
0
 
LVL 17

Expert Comment

by:zzzzzooc
Comment Utility
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 "window.open('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...

<SCRIPT LANGUAGE="JavaScript">
var Test1='StringTest1';
var Test2=Test1;
var Test3=Test2;
</SCRIPT>
0
 
LVL 17

Expert Comment

by:zzzzzooc
Comment Utility
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
0
 
LVL 1

Author Comment

by:TrevorParnhamntl
Comment Utility
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.
0
 
LVL 1

Expert Comment

by:livepersoninc
Comment Utility
'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 = ""
    Clipboard.Clear
    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
    Do
          DoEvents
    Loop While WebBrowser1.Busy
 
' Set focus to the text box and then paste
    txtData.SetFocus
    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
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now