Site hosted by Angelfire.com: Build your free website today!
undefined
undefined

Richie's Internet Explorer & Web Browser control

DOM Tips

Hello, these are some tips that i have been learning from time to time. Most of them have something in common: they comes to light due to questions posted at EE. Basically, in Visual Basic Area.
Hope you font them useful and enjoy them as me. Thanks for reading ;).
Level: Intermediate

Contents:

Override default popup menu - Web Browser Control
Create a new Standard exe project.
Add a reference to Microsoft HTML Object Library.
Add Internet Browser control to your Toolbox.
Add the following controls:
1 textbox
   Text = "Whatever you want"
1 Command button
   Caption = "&Go!"
   Default = True
1 Webbrowser control
   Name = wb1
Your window should looks like the following picture:



On General Declaration section of form1, we need to declare variables:
Private WithEvents HDoc As HTMLDocument
With this variable, we will manage Properties/Methods and most important: Events from our target HTML Document.
The question here is: why we need a variable of type HTMLDocument?
We need it because Webbrowser1.document (which is the same object type) doesn't expose their events and we need them to gain access to an important one: onmousedown.
Besides, we will get Autolist Members feature from HDoc that, otherwise, we would miss from Webbrowser.document in VB IDE.
As soon as variable is created, we can access it like any other object that belongs to form1 in the Code Pane.
To set HDoc to our current loaded document, we need to set objects in the DocumentComplete event of webbrowser because until document is fully loaded, we can't access it. More, if you want to override menu, but only for a given location, you have to check it there too.
Private Sub WB1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is WB1.Object) Then
    Text1.Text = URL
    ' Change url www.experts-exchange.com to what url you want to avoid.
    ' Optionally, instead of hard-coded value, you could store in
    ' another textbox control.
    If UCase$(URL) = "WWW.EXPERTS-EXCHANGE.COM" Then
        Set HDoc = WB1.document
    End If
End If
End Sub
The If (pDisp Is WB1.Object) Then... statement is necessary due to the fact that page loaded could contains frames and this event is fired for each of them.
From here, we have plenty access to document inside webbrowser control.
When we right-click on the document, the first event that is fired is onmousedown, and it is the event we need to manage.
To do things short, i trapped some tags only. You could manage all of them. This is the code from onmousedown event:
Private Sub HDoc_onmousedown()
' Creating a variable to hold elements inside document object,
' and pull off those awful dots that eat resources.
Dim Elem As IHTMLElement
Set Elem = HDoc.parentWindow.event.srcElement
With Elem
    ' Check if button = 2 (right button) was pressed.
    ' Otherwise, we don't do anything.
    If HDoc.parentWindow.event.button = 2 Then
    Dim msg As String
        Select Case UCase$(.tagName)
        Case "A"
            ' Change url to one of your test page ;)
            If UCase$(.href) = _
               UCase$("http://www.experts-exchange.com/jsp/qList.jsp?ta=visualbasic") Then
                msg = "you right-clicked on " & vbNewLine & .href
                MsgBox msg, vbInformation, App.EXEName
            End If
        Case "BODY"
           msg = "This HTML code is mine!"
        Case "IMG"
            msg = "Imágen"
        Case "P"
            msg = "Para"
        Case "H1"
            msg = "Header: size 1"
        End Select
        Me.Caption = "Click on " & msg
    End If
End With
End Sub
The following picture shows the result of do a right-click on a link in a test page (that i trapped with previous code).



What we are doing there is check for value of tagName property. If tag name is one of we already trapped, we write its type on caption of form1, just to show that it works.
The only Popup menu what we are overriding is for anchor tag, all others are trapped but not overriding.
You could create your own menu (See Visual Basic help to know how) in form1 to responds to each Case statement.
Following is the code for Form_Load and Command1_Click events.
Private Sub Form_Load()
WB1.navigate "about:blank"
End Sub

Private Sub Command1_Click()
With Text1
    If .Text <> "" Then WB1.navigate .Text
End With
End Sub
That's all.
Little code, don't you think so?.

Override default popup menu - Internet Explorer Object
Basically, it's almost the same. Here are those diferences:
Create a new exe project.
Add a reference to Microsoft HTML Object Library.
Add a reference to Microsoft Internet Controls.
Add the following controls:
1 textbox
   Text = "Whatever you want"
1 Command button
   Enabled = False
   Caption = "&Go!"
   Default = True

On General Declaration section of form1, we need to declare variables:
Private WithEvents HDoc As HTMLDocument
Private WithEvents IE as InternetExplorer
... WithEvents IE ... is necessary to gain access to DocumentComplete event.
In that event, we add code similar to previous one:
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
    Text1.Text = URL
    ' Change url WWW.MICROSOFT.COM to what url you want to avoid.
    ' Optionally, Instead of hard-coded value, you could store in
    ' another textbox control.
    If UCase$(URL) = "WWW.MICROSOFT.COM" Then
        Set HDoc = IE.document
    End If
End If
End Sub
From here, the code is the same ...
Private Sub HDoc_onmousedown()
' Creating a variable to hold elements inside document object,
' and pull off those awful dots that eat resources.
Dim Elem As IHTMLElement
Set Elem = HDoc.parentWindow.event.srcElement
With Elem
    ' Check if button = 2 (right button) was pressed.
    ' Otherwise, we don't do anything.
    If HDoc.parentWindow.event.button = 2 Then
    Dim msg As String
        Select Case UCase$(.tagName)
        Case "A"
            ' Change url to one of your test page ;)
            If UCase$(.href) = _
               UCase$("http://www.experts-exchange.com/jsp/qList.jsp?ta=visualbasic") Then
                msg = "you right-clicked on " & vbNewLine & .href
                MsgBox msg, vbInformation, App.EXEName
            End If
        Case "BODY"
           msg = "This HTML code is mine!"
        Case "IMG"
            msg = "Imágen"
        Case "P"
            msg = "Para"
        Case "H1"
            msg = "Header: size 1"
        End Select
        Me.Caption = "Click on " & msg
    End If
End With
End Sub
...with this little diference:
Private Sub Form_Load()
Set IE = New InternetExplorer    ' Creates new Internet Explorer Instance
If Not IE is Nothing then
   Command1.Enabled = True
   With IE
        .navigate "about:blank"
        .visible = True
   End With
End If
End Sub

Private Sub Command1_Click()
With Text1
    If .Text <> "" Then IE.navigate .Text
End With
End Sub

Meta Tags - Internet Explorer
Create a new Standard exe project.
Add a reference to Microsoft HTML Object Library.
Add a reference to Microsoft Internet Controls.
Add the following controls:
2 TextBox
1 CommandButton
1 ListBox
Your form could be like this:



This little app shows the names and contents of meta-tags for a given page. It only works with Internet Explorer.
Option Explicit
Dim WithEvents IE As InternetExplorer
Dim oMetaTags() As HTMLMetaElement
Dim sUrl As String

Private Sub Command1_Click()
IE.navigate Text1.Text
End Sub

Private Sub Form_Load()
Set IE = New InternetExplorer
With IE
    .navigate "about:blank"
    .Visible = True
End With
End Sub

Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp is IE) Then
    Dim t As HTMLMetaElement, idx As Integer
    Dim hdoc As HTMLDocument
    Set hdoc = IE.document
    With List1
        .Clear
        For Each t In IE.document.All.tags("META")
            ReDim Preserve oMetaTags(idx)
            If t.Name = "" Then
                .AddItem "[None]"
            Else
                .AddItem t.Name
            End If
            Set oMetaTags(idx) = t
            idx = idx + 1
        Next
    End With
    If URL = "about:blank" Then
        sUrl = "about:blank"
    Else
        sUrl = IE.document.Title
    End If
End If
End Sub

Private Sub List1_Click()
With Text2
    .Text = ""
    .Text = oMetaTags(List1.ListIndex).content
End With
End Sub

Hide scrollbar - Web Browser Control
Create a new Standard exe project.
Add Internet Browser control to your Toolbox.
Add the following controls:
1 Webbrowser control
   Name = WB1 To this time, i think that the only person who knows this trick is me.
On all forums that i have been visiting is the old same thing: How could i hide scroll bar from WebBrowser control?.
The answer always is: Put inside a PictureBox control and set PictureBox's Width (or, ScaleWidth, i just don't remember ;) to WebBrowser control minus scroll bar width.
To me, that is a waste of resources. So i did a little dig and got the following:
' On Declarations section of the form
' that has WebBrowser control.
Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As Long) As Long
Paste this code in Form_Load event:
WB1.navigate "www.angelfire.com"
' And just in case you don't know exact width:
Const SM_CXVSCROLL = 2
Dim ret As Long
ret = GetSystemMetrics(SM_CXVSCROLL)
WB1.Width = WB1.Width - (ret * Screen.TwipsPerPixelX)
And paste this code in DocumentComplete event of WB1 control:
Private Sub WB1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is WB1.Object) Then
    WB1.Document.body.setAttribute "scroll", "no"
End If
End Sub
Voilà!. say goodbye to scrollbar.
But, it has an awful behaviour: If you refresh the page, scroll bar shows again!.
To avoid this unwanted "error", we have to handle one more event.
Private Sub WB1_DownloadComplete()
  WB1.Document.body.setAttribute "scroll", "no"
End Sub
There is another way too, see the following code:
Private Sub WB1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is WB1.Object) Then
    WB1.Document.body.style.overflow ="hidden"
End If
End Sub
You can implement this with an Internet Explorer Object, just as we have been reading from previous tips. I mean, instead of using wb1 object, declare an object variable (withevents) of type InternetExplorer and put that code inside appropiate events.

Select all contents of active web page - Internet Explorer Object
As always, we will manage DocumentComplete event:
' This code assumes that you already have declared
' a variable of type Internet Explorer called IE.
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
    With IE
         .ExecWB OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT
         .ExecWB OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT
    End With
End If
End Sub
With previous code you have selected entire contents of web page and put it in clipboard, ready to paste wherever you want.

How about copying only selected text?
Well, we need some more objects variables to get it:
' In general declaration section of main form
Dim WithEvents IE As InternetExplorer
Dim WithEvents HDoc As HTMLDocument  'We need to know when user does something with his mouse.
Dim TxtRng As IHTMLTxtRange   ' To manage selected text.
As always, we got handle to document object in DocumentComplete event.
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
    Set HDoc = IE.document
End If
End Sub
To select text, user has to use the mouse. So, we will trap only one event to set our TextRange.
These are (in order) the actions that takes place when user selects text from web page:
  1. Mouse Down
  2. Mouse Drag
  3. Mouse Up
We will trap the last one since there is when selection finish:
Private Sub HDoc_onmouseup()
' We create a TextRange based upon user's selection
Set TxtRng = HDoc.selection.createRange

' We can change text selected if we want...
'TxtRng.Text = "It works!"

' ...or copy it to clipboard
IE.ExecWB OLECMDID_COPY, OLECMDEXECOPT_DONTPROMPTUSER
End Sub

Login automation - Internet Explorer & Web Browser Control
Sometimes, we need to login to gain access to complete site. I will show you a way to log to www.hotmail.com, which requires user id, password and to push a button.
Before go further showing code, we need to know how login process takes place.
Sites needs to know where you enter things and we need too. Generally, textboxes used to enter id and password have names to diferentiate among others textboxes and it is marvelous. We need those names too.

Those names are located inside HTML code. We have to "read" HTML code the first time we access login page.

To this time, i already did that. The textbox name for user id is: login and textbox name for password is: passwd. The name of the button we need to press is: enter.

By now, you already know how to set object variables for InternetExplorer and you have been using WebBrowser control, so, i will not explain here again.
Private Sub Form_Load()
set IE = New InternetExplorer
With IE
     .navigate "www.hotmail.com"
     .visible = True
End With
End Sub
Let's go to DocumentComplete event:
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
    If InStr(1, URL, "passport.com/cgi-bin/login", vbTextCompare) Then
            Dim inp As Object
            Set inp = IE.document.all.Item("login")
            inp.Value = "myname"  'replace with your id
            
            Set inp = IE.document.all.Item("passwd")
            inp.Value = "passwrd"  'replace with your password
            
            Set inp = IE.document.all.Item("enter")
            inp.Click
     End if
End If
End Sub
A variation:
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
    If InStr(1, URL, "passport.com/cgi-bin/login", vbTextCompare) Then
            IE.document.all.Item("login").value = "myname"  'replace with your id
            
            IE.document.all.Item("passwd").Value = "passwrd"  'replace with your password
            
            IE.document.all.Item("enter").Click
     End if
End If
End Sub
We are almost finish. To actually read mails from Hotmail, you need one more click. I will let you know how to automate this by yourself.

Hope you have enjoyed that work as i did.
;)


©2001 - Richie Simonetti