# VBForums CodeBank > CodeBank - Visual Basic 6 and earlier >  Webbrowser Control Tip and Examples

## wiz126

*Webbrowser control*
Since I have been seen lately many people asking questions about the webbrowser control.

First of all the webbrowser control is not one of the controls that come by default in the control box. All you have to do to add it there is to press Ctrl + T key or  (Project -> Components using the menu). Once in the components select window scroll down and check the box next to Microsoft Internet Controls and click ok.

Examples:
Navigating to a sitePopup browser using your own formCheck if word/string is found on the pageMaking page on startupRegular Browser FunctionsAdvanced browser functionsChanging web browsers Font SizeDisabling functions appropriately (Back/Forward)Disabling functions appropriately (page setup/print preview/print setup)Removing Right Click Menu From the browser controlGrab all links on the pageSave PageOpen PageAuto SubmitUsing A ProgressBar With The WebbrowserSetting a Control in a Webbrowser to focusCheckbox in a page, how to control itCustom Right Click Menu

*Navigating to a site:*
Navigating to a site...

VB Code:
WebBrowser1.Navigate "www.google.com"
*Opening a popup window with your app*
If the user go to a site where a new page needs to come in a new browser this code is made to open the target site in a new form.

VB Code:
Private Sub WebBrowser1_NewWindow2(ppDisp As Object, Cancel As Boolean)
Dim frm As Form1
Set frm = New Form1
Set ppDisp = frm.WebBrowser1.Object
frm.Show
End Sub
*Check if word/string is found on the page*
This code will let you check the page for a word or a sentence.

VB Code:
Private Sub Command1_Click()
    Dim strfindword As String
        strfindword = InputBox("What are you looking for?", "Find", "") ' what word to find?
            If WebPageContains(strfindword) = True Then 'check if the word is in page
                MsgBox "The webpage contains the text" 'string is in page
            Else
                MsgBox "The webpage doesn't contains the text" 'string is not in page
            End If
End Sub
Private Function WebPageContains(ByVal s As String) As Boolean
    Dim i As Long, EHTML
    For i = 1 To WebBrowser1.Document.All.length
        Set EHTML = _
        WebBrowser1.Document.All.Item(i)
          If Not (EHTML Is Nothing) Then
            If InStr(1, EHTML.innerHTML, _
            s, vbTextCompare) > 0 Then
            WebPageContains = True
            Exit Function
        End If
    End If
Next i
End Function
Private Sub Form_Load()
    WebBrowser1.Navigate2 "www.msn.com"
End Sub
*Making page on startup*
This code show you how to make a page and show it on event.

VB Code:
Private Sub Form_Load()
    WebBrowser1.Navigate "about**:blank"
End Sub
 Private Sub Command1_Click()
    Dim HTML As String
        '----------The HTML CODE GOES FROM HERE AND DOWN----------
    HTML = "<HTML>" & _
            "<TITLE>Page On Load</TITLE>" & _
            "<BODY>" & _
            "<FONT COLOR = BLUE>" & _
            "This is a " & _
            "<FONT SIZE = 5>" & _
            "<B>" & _
            "programmatically " & _
            "</B>" & _
            "</FONT SIZE>" & _
            "made page" & _
            "</FONT>" & _
            "</BODY>" & _
            "</HTML>"
            '----------The HTML CODE GOES HERE AND ABOVE----------
    WebBrowser1.Document.Write HTML
End Sub
*Regular Browser Functions*
This are the basic internet browser's functions.

VB Code:
Private Sub Command1_Click(Index As Integer)
On Error Resume Next ' just in case there is no page back or forward
                    'I showed how to disabel them if you scroll down more
    Select Case Index
        Case 0 'Go Back Button
            WebBrowser1.GoBack 'Go Back one Page
        Case 1 'Go Forward Button
            WebBrowser1.GoForward 'Go Forward one Page
        Case 2 'Stop Button
            WebBrowser1.Stop 'stop page
        Case 3 'Refresh Button
            WebBrowser1.Refresh 'refresh page
        Case 4 'Go Home Button
            WebBrowser1.GoHome 'Go to home page
        Case 5 'Search Button
            WebBrowser1.GoSearch 'Search
    End Select
End Sub
*Advanced Browser Functions*
This are the more complex browser functions like print and page Properties.

VB Code:
Private Sub Command1_Click() 'Print Button
    WebBrowser1.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DODEFAULT 'Show Print Window
End Sub
Private Sub Command2_Click() 'Print Preview Button
    WebBrowser1.ExecWB OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DODEFAULT 'Show Print Preview Window
End Sub
Private Sub Command3_Click() 'Page Setup Button
    WebBrowser1.ExecWB OLECMDID_PAGESETUP, OLECMDEXECOPT_DODEFAULT 'Show Page Setup Window
End Sub
Private Sub Command4_Click() 'Page Properties Button
    WebBrowser1.ExecWB OLECMDID_PROPERTIES, OLECMDEXECOPT_DODEFAULT 'Show Page Properties Window
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
*Changing web browsers Font Size*
This Code shows you how to change the page font size, just like internet explorer View -> Text Size Menu

VB Code:
Private Sub Command1_Click() ' Smallest Button
On Error Resume Next
    WebBrowser1.ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(0), vbNull
End Sub
Private Sub Command2_Click() 'Small Button
On Error Resume Next
    WebBrowser1.ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(1), vbNull
End Sub
Private Sub Command3_Click() 'Medium Button
On Error Resume Next
    WebBrowser1.ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(2), vbNull
End Sub
Private Sub Command4_Click() 'Large Button
On Error Resume Next
    WebBrowser1.ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(3), vbNull
End Sub
Private Sub Command5_Click() 'Largest Button
On Error Resume Next
    WebBrowser1.ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(4), vbNull
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate2 "www.google.com"
End Sub
*Disabling functions appropriately (Back/Forward)*
This code shows you how to appropriately disable the back and forward button.

VB Code:
Private Sub Command1_Click() 'Go Back Button
    WebBrowser1.GoBack 'Go Back
End Sub
Private Sub Command2_Click() 'Go Forward Button
    WebBrowser1.GoForward 'Go Forward
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
Private Sub WebBrowser1_CommandStateChange(ByVal Command As Long, ByVal Enable As Boolean)
    Select Case Command
        Case 1 'Forward
            Command2.Enabled = Enable
        Case 2 'Back
            Command1.Enabled = Enable
    End Select
End Sub
*Disabling functions appropriately (page setup/print preview/print setup)*
This code shows you how to appropriately disable the page setup or print setup.

VB Code:
Private Sub Command1_Click() 'Print Button
    WebBrowser1.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DODEFAULT 'Show Print Window
End Sub
Private Sub Command2_Click() 'Print Preview Button
    WebBrowser1.ExecWB OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DODEFAULT 'Show Print Preview Window
End Sub
Private Sub Command3_Click() 'Page Setup Button
    WebBrowser1.ExecWB OLECMDID_PAGESETUP, OLECMDEXECOPT_DODEFAULT 'Show Page Setup Window
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
Public Function Enable_or_Disable()
    If WebBrowser1.QueryStatusWB(OLECMDID_PRINT) = 0 Then
        Command1.Enabled = False
    Else
        Command1.Enabled = True
    End If
    If WebBrowser1.QueryStatusWB(OLECMDID_PRINTPREVIEW) = 0 Then
        Command2.Enabled = False
    Else
        Command2.Enabled = True
    End If
     If WebBrowser1.QueryStatusWB(OLECMDID_PAGESETUP) = 0 Then
        Command3.Enabled = False
    Else
        Command3.Enabled = True
    End If
End Function
Private Sub WebBrowser1_BeforeNavigate2 _
                    (ByVal pDisp As Object, _
                                URL As Variant, _
                                Flags As Variant, _
                        TargetFrameName As Variant, _
                                PostData As Variant, _
                                    Headers As Variant, _
                                        Cancel As Boolean)
    Enable_or_Disable
End Sub
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    Enable_or_Disable
End Sub
*Removing Right Click Menu From the browser control*
So you need to remove the right click menu from the control, right? well there are more then two ways one of them, which i knew but i won't bother telling is using lots of hooking, waist of thime since all you have to do is download a simple helper file.
First you need to go to http://support.microsoft.com/kb/q183235/ and download the WBCustomizer.dll. once done go to the"Project Menu" and click on "Refrences" Click on browse and add the 'WBCustomizer.dll' to you app. once done just add this simple code.

VB Code:
Option Explicit
    Dim CustomWB As WBCustomizer 'Deceler the CustomWB
Private Sub Form_Load()
   Set CustomWB = New WBCustomizer
   With CustomWB
      .EnableContextMenus = False 'Disable The Menu
      .EnableAllAccelerators = True
      
      Set .WebBrowser = WebBrowser1
   End With
    WebBrowser1.Navigate "www.google.com"
        CustomWB.EnableContextMenus = False
End Sub

----------


## wiz126

*Grab all links on the page*
This code shows how to grab and list all the links on a page, this can be used a spider software for a search engine site.
In order to get this code to load you must add the "Microsoft HTML Object Library" into your app refrences.

VB Code:
Option Explicit
Private Sub Form_Load()
    WebBrowser1.Navigate "www.vbforums.com"
End Sub
Private Sub WebBrowser1_DownloadComplete()
    'you must add the "Microsoft HTML Object Library"!!!!!!!!!
    Dim HTMLdoc As HTMLDocument
        Dim HTMLlinks As HTMLAnchorElement
            Dim STRtxt As String
    ' List the links.
    On Error Resume Next
        Set HTMLdoc = WebBrowser1.Document
            For Each HTMLlinks In HTMLdoc.links
                STRtxt = STRtxt & HTMLlinks.href & vbCrLf
            Next HTMLlinks
        Text1.Text = STRtxt
End Sub
You can add this code in order to log this files.

VB Code:
Open "C:\Documents and Settings\[YOU USERNAME]\Desktop\link log.txt" For Append As #1
Print #1, STRtxt
Close #1
*Save Page*
This code shows you how to save the browser's page.

VB Code:
Option Explicit
Private Sub Command1_Click()
WebBrowser1.ExecWB OLECMDID_SAVEAS, OLECMDEXECOPT_DODEFAULT
End Sub
Private Sub Form_Load()
WebBrowser1.Navigate2 "www.google.com"
End Sub
*Open Page*
Here is how to load a webpage into the webbrowser.

VB Code:
Private Sub Command2_Click()
    WebBrowser1.ExecWB OLECMDID_OPEN, OLECMDEXECOPT_PROMPTUSER
End Sub
This is how to open a page, using the comman dialog's way

VB Code:
Option Explicit
Private Sub Command1_Click()
On Error Resume Next
    With CommonDialog1
        .DialogTitle = "Open File"
        .Filter = "Web page (*.htm;*.html) | *.htm;*.html|" & _
        "All Supported Picture formats|*.gif;*.tif;*.pcd;*.jpg;*.wmf;" & _
        "*.tga;*.jpeg;*.ras;*.png;*.eps;*.bmp;*.pcx|" & _
        "Text formats (*.txt;*.doc)|*.txt;*.doc|" & _
        "All files (*.*)|*.*|"
        .ShowOpen
        .Flags = 5
    WebBrowser1.Navigate2 .FileName
    End With
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate2 "www.google.com"
End Sub
*Auto Submit*
This Simple Code I Made To show you how to make a submittion form. This code will autofill the need filled and submit it.

VB Code:
Private Sub Command1_Click()
Dim strwebsite As String
    Dim stremail As String
        strwebsite = "http://www.mysite.com"
            stremail = "myemail@host.com"
WebBrowser1.Document.addurl.URL.Value = strwebsite
    WebBrowser1.Document.addurl.Email.Value = stremail
        WebBrowser1.Document.addurl.Submit
End Sub
Private Sub Form_Load()
    WebBrowser1.Navigate "http://www.scrubtheweb.com/addurl.html"
End Sub
*Using A ProgressBar With The Webbrowser* 
This is to show how to use a progressbar with a webbrowser control.

VB Code:
Private Sub Form_Load()
    WebBrowser1.Navigate "www.msn.com"
    ProgressBar1.Appearance = ccFlat
    ProgressBar1.Scrolling = ccScrollingSmooth
End Sub
 Private Sub WebBrowser1_ProgressChange(ByVal Progress As Long, ByVal ProgressMax As Long)
On Error Resume Next
    If Progress = -1 Then ProgressBar1.Value = 100
        Me.Caption = "100%"
    If Progress > 0 And ProgressMax > 0 Then
        ProgressBar1.Value = Progress * 100 / ProgressMax
        Me.Caption = Int(Progress * 100 / ProgressMax) & "%"
    End If
    Exit Sub
End Sub
*Setting a Control in a Webbrowser to focus*
This shows how to set a control inside the webbrowser into focus.

VB Code:
Private Sub Command1_Click()
    WebBrowser1.Document.All("q").focus 'Set the search text filed in focus
End Sub
 Private Sub Command2_Click()
    WebBrowser1.Document.All("btnI").focus 'Set the google "I Am feeling lucky in focus button"
End Sub
 Private Sub Form_Load()
    WebBrowser1.Navigate "http://www.google.com/"
End Sub

Or you can use:

VB Code:
WebBrowser1.Document.getElementById("Object's Name").Focus
*Checkbox in a page, how to control it*
This is an example on how to check or uncheck the remember me checkbox on the google login page:


VB Code:
Private Sub Form_Load()
WebBrowser1.Navigate "https://www.google.com/accounts/ManageAccount"
End Sub
Private Sub Check1_Click()
    If Check1.Value = 0 Then
        WebBrowser1.Document.All.PersistentCookie.Checked = False 'unchecked
    Else
        WebBrowser1.Document.All.PersistentCookie.Checked = True 'checked
    End If
End Sub
Or


VB Code:
Private Sub Form_Load()
WebBrowser1.Navigate "https://www.google.com/accounts/ManageAccount"
End Sub
Private Sub Check1_Click()
    If Check1.Value = 0 Then
        WebBrowser1.Document.All.PersistentCookie.Checked = 0 'unchecked
    Else
        WebBrowser1.Document.All.PersistentCookie.Checked = 1 'checked
    End If
End Sub
Or

VB Code:
Private Sub Form_Load()
WebBrowser1.Navigate "https://www.google.com/accounts/ManageAccount"
End Sub
Private Sub Check1_Click()
    If Check1.Value = 0 Then
        WebBrowser1.Document.getElementById("PersistentCookie").Checked = False 'unchecked
    Else
        WebBrowser1.Document.getElementById("PersistentCookie").Checked = True 'checked
    End If
End Sub
*Custom Right Click Menu*
This is an example show how to make your own custom right click menu. in order for this to work you must add the "Must Add Microsoft HTML Object Library" to your refrance.Also make your own custom menu using the menu editor I named my "mnu"
Please Note it will effect all the context menus in the webbrowser.


VB Code:
'Must Add Microsoft HTML Object Library
Option Explicit
    Public WithEvents HTML As HTMLDocument
 Private Function HTML_oncontextmenu() As Boolean
   HTML_oncontextmenu = False
   PopupMenu mnu '<---Check the mnu to your own menu name
End Function
 Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
 Private Sub Form_Unload(Cancel As Integer)
   Set HTML = Nothing
End Sub
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, _
                                                 URL As Variant)
   Set HTML = WebBrowser1.Document
End Sub

----------


## wiz126

~~~~~~~...:::Toturial Updates:::...~~~~~~~
01-27-2006 06:25 PM - Main Toturial 
01-27-2006 06:33 PM- Save/Open Page ,  Grab Links On Page
02-07-2006 06:14 PM - Auto Submitting
02-14-2006 03:16 PM - Using A ProgressBar With The Webbrowser
03-22-2006 06:03 PM - Checkbox in a page

----------


## oasa

I didnt Knew that one can disable Right Click on that. i guess that works. Well can you say how to enable AJAX on one. and how to add a menu on existing rightclick.

----------


## Pacca

how can i add center click???

----------


## wiz126

> I didnt Knew that one can disable Right Click on that. i guess that works. Well can you say how to enable AJAX on one. and how to add a menu on existing rightclick.


Looks like I indeed forgat to show how, well I just added "Custom Right Click Menu" and i showed how to have your how popup right click menu




> how can i add center click???


Are you talking about the middle (wheel) button? if yes then, I don't think you can, You might globaly (in the whole app). I will try playing with some code see if i can get it to work.

----------


## Pacca

> Are you talking about the middle (wheel) button? if yes then, I don't think you can, You might globaly (in the whole app). I will try playing with some code see if i can get it to work.


yes about this

----------


## Pacca

nobody can help me???

----------


## wiz126

Try making the webbrowser control in a custom control and see if you can catch the middle button. Otherwise I guess its not possible in visual basic 6 (atleast)

----------


## softcom

Hi,
I've been trying the example to change the font size and I typed in the vb 6 code and I have the internet control added.

With WebBrowser1
   .Navigate strAddress
   .ExecWB OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, CLng(4), vbNull
End With

I keep getting 
Method 'ExecWB' of object 'IWebBrowser2' failed.  as the error message
I even tried CLng(1)

Thanks for the help
Brian

----------


## penagate

Example here  :Smilie:

----------


## shirazamod

Good tips for beginners   :Thumb:

----------


## Pacca

a littler problem...
i disabled the right click menu and i made my own...now i need a code for a button in the menu that when i click on a link it comes the menu "open in a new page"...can any1 help me?

----------


## Pacca

no solutions?

----------


## titpu

Hi all, 

I know how to auto submit form using form name. now i want submit form using form id. How to do that?

----------


## dankasolutions

How about autoscroll function? Could you introduce more?

----------


## wiz126

> How about autoscroll function? Could you introduce more?


Can you explain more on what you are looking for?

----------


## dankasolutions

I mean that could you introduce how to make a web browser control can autoscroll its content.

----------


## kazar

Nice code.  Two questions tho.  One, does the link getting function also get image links?  or just text links.  And secondly is there a way to get all the srcs of a webpage, i.e. images, css files, etc.

----------


## penagate

Get page source:

VB Code:
Dim pageSource As String
pageSource = webBrowser.document.body.parentElement.innerHTML

Get images:

VB Code:
Dim pageImages As Object
pageImages = webBrowser.document.getElementsByTagName("img")

Get links:

VB Code:
Dim pageLinks As Object
pageLinks = webBrowser.document.getElementsByTagName("a")

Get image links:

VB Code:
Dim pageImageLinks As Collection
Dim pageLinks As Object
pageLinks = webBrowser.document.getElementsByTagName("a")
 Dim link As Object
Dim linkChildren As Object
For Each link In pageLinks
  linkChildren = link.getElementsByTagName("img")
  ' Can't remember if this next bit will work, might need fiddling
  If (linkChildren.Count) _
    pageImageLinks.Add(link)
Next

Bear in mind it's a while since I've used VB, most of that is converted from JS.

----------


## kazar

I found the solution:


VB Code:
Dim HTMLdoc As HTMLDocument
Dim pageImages As HTMLImg
                
   HTMLDoc = Webbrowser1.Document
             
     For Each pageImages In HTMLdoc.images
                   
                   List2.AddItem pageImages.src
      Next pageImages

----------


## jammin17

Is there any way to fill an input box type = "file" with a filename to upload automatically in the webbrowser?  I can't seem to get this to work.  I can fill in everything else and click submit, but I can not get the filename to show up in the input box.  Any suggestions?

jam  :wave:

----------


## litlewiki

Alright,i have a question.when i connect to a website,the server identifies the make and version of my browser.Now is it possible to change the header info? for eg i want my app to be identified as a mozilla browser and not a ie one.I think it is possible with the ".ExecWb" method .Can someone give me an example ?

----------


## kazar

I do not think that you can change the headers using the webbrowser.  I think you can do it using the inet control execute method.  Then you could write the recieved code to the browser.

----------


## kazar

Hey, 

How could i  get the src's of all the objects on the page. e.g. flash player, movie, etc.

Thanks

----------


## DssTrainer

Hmm.. I'm having trouble with radio buttons on webforms. What is the value to set for "selected" ? I tried getting the value and it gives me a EMPTY for the variable set for that value even when it's checked. shipFromZipCode is the name of the radio button.

x = WebBrowser1.Document.Forms(0).shipFromZipCode.Value

----------


## DssTrainer

I figured it out.. For radio buttons, since they are typically linked to the disabling of other buttons, they all share the same name but different ID. so instead of the name, you need to use the ID. You can also use value or checked depending on what property format you want.

----------


## osemollie

After reding through this tutorial, I was faced by a challenge. Am making my page using "Making page on startup" tips where I create a HTML string. Now, I want to display values from a database, how do I call these values into the HTML? I have my recordset ready and what is remaining is calling the values onto the page. I will appreciate your help.

Thanks.

----------


## vnviews

This thread makes me registering. Excellent! Thank you.
I am developing a software that uses web control, but having a small problem:
When I want to have number of controls in form, it would be document.forms(i).length, right?
But if form has control with name "length", it returns reference to this control and I can't have what a I'm looking for.
Can anyone help me with that?
Thank you very much.
Tuan.

----------


## Zookeeper

Is there any way to view pages in the Web Browser control with the page controls (buttons, check boxes, etc.) adopting the XP style as IE6 already does.  I know there is a way using a resouce file to get most of the Windows Common Controls to adopt the XP them.  Is there a similar way to get the Web Browser control to do this?

----------


## longwolf

It sure would be nice if VB6 had intelisence(?) to  go with the browser control.
I just found wbrBrowser.Document.Title and I know it has wbrBrowser.Document.documentElement.

Does anyone know where to get a list of the full model?
Or at least a good part of it?

Right now I'm trying to find out how to pull the Meta Tags, but haven't got a clue where to find them.

I could write a string parser to get them, but it'd be nice just to use the control itself.

----------


## penagate

You need to reference the Microsoft HTML Object Library and cast wbrBrowser.Document into a HTMLDocument type.


VB Code:
Dim doc As HTMLDocument
Set doc = wbrBrowser.Document

----------


## longwolf

Thanks Penagate.
That should be a big help!

I'm still lost in there without a help file, but at least that gives some road signs.

I'm trying to find the Meta tags and FavIcon, if they have one.



```
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="description" content="Visual Basic Discussions plus .NET, C#, game programming, and more (http://www.VBForums.com)" />
```

----------


## penagate

Check the type names

VB Code:
Dim favicon As String
Dim description As String
 Dim links As HTMLElementCollection
Dim metas As HTMLElementCollection
 Set links = wbrBrowser.Document.GetElementsByTagName("link")
Set metas = wbrBrowser.Document.GetElementsByTagName("meta")
 Dim link As HTMLLinkElement
For Each link In links
  If (InStr(link.GetAttribute("rel"), "icon") Then
    favicon = link.GetAttribute("href")
    Exit For
  End If
Next
 Dim meta As HTMLMetaElement
For Each meta In metas
  If (meta.HasAttribute("description")) Then
    description = meta.GetAttribute("content")
    Exit For
  End If
Next

Hope that helps.

For documentation see DOM - MDC.

----------


## longwolf

I'm getting Type Mismatch errors on both of these.

VB Code:
Set links = wbrBrowser.Document.getElementsByTagName("link")
Set metas = wbrBrowser.Document.getElementsByTagName("meta")

I have added the reference to the Microsoft HTML Object Library .

----------


## penagate

odd, try MSHTML.HTMLElementCollection

Failing that, look in the Object Browser and see what getElementsByTagName returns.

----------


## longwolf

Looks like I got it.

VB Code:
Dim myHTMLDoc As New HTMLDocument
Dim colA As IHTMLElementCollection
Dim myA As IHTMLElement
     Set myHTMLDoc = wbrBrowser.Document 
    Set colA = myHTMLDoc.getElementsByTagName("link")
    For Each myA In colA
        If LCase(myA.getAttribute("rel")) = "shortcut icon" Then
            Debug.Print myA.getAttribute("href")
            Exit For
        End If
    Next
    
    Set colA = myHTMLDoc.getElementsByTagName("meta")
    For Each myA In colA
        If LCase(myA.getAttribute("name")) = "description" Then
            Debug.Print myA.getAttribute("content")
        End If
    Next
    
    Set myA = Nothing
    Set colA = Nothing
    Set myHTMLDoc = Nothing

Thanks for your help Penagate!

----------


## longwolf

BTW, do I need the LCase's I used or are the elements always returned as lower case?

----------


## penagate

> BTW, do I need the LCase's I used or are the elements always returned as lower case?


 They're returned as specified in the source. So, LCases are a good idea.  :Smilie:

----------


## jawadaq82

Dear 1 Heartly appreciate your this briefly lesson on Webbrowser
here 1 m facing a problem.

I wanna pick some text from a table cell like in blow table I need to pick 
1.(216)216-2167
2."NO" 
3. "0%"

<TABLE WIDTH="100%" CELLSPACING="1" CELLPADDING="3" BORDER="0">
<TR CLASS="backgroundborderpeach" ALIGN="center">
<TD>10-Digit Phone Number</TD><TD>Approved</TD><TD>Rebate Percentage</TD></TR>
<TR ALIGN="center" CLASS="backwhite1">
<TD>(216)216-2167</TD><TD>No</TD><TD>0%</TD></TR>
</TABLE>

------------------------------------------------------------------------------------------------
and in this table I need to pock
1.Qualifies for 100% On Dec 1, 2008
where Number of % can be changed like 10% or 50%

<TABLE WIDTH="100%" CELLSPACING="1" CELLPADDING="3" BORDER="0">
<TR><TD>&nbsp;</TD></TR>
<TR CLASS="backwhite1"><TD><IMG SRC="/ec/images/leftarrow.gif" width="35px" BORDER="0"> <SPAN CLASS="HEAVY">Qualifies for 100% On Dec 1, 2008</SPAN></TD></TR></TABLE>


so PLZ guide me to do this.

----------


## Miha2c30

When I click 'Open', it doesn't want to. It doesn't show any errors or anything, nothing happens.


VB Code:
Private Sub menuFileOpen_Click()
wWeb.ExecWB OLECMDID_OPEN, OLECMDEXECOPT_PROMPTUSER
End Sub

Can anyone help me?

----------


## msgjp7

Hello,
I'm using this code from a previous example in thread.

Private Sub Command1_Click()    
WebBrowser1.Document.All("q").focus 
End Sub

Private Sub Form_Load()    
WebBrowser1.Navigate "http://www.google.com/"
End Sub 

It all works great. But due to the lack of documentatiion I can seem to find a way of entering something in the text box and then reloading the page. Any help would be greatly appreciated. Or even a link to some documentation would work too.

Thanks

----------


## msgjp7

Figured it out. Just in case anyone is interested, this works.



```
WebBrowser1.Document.All("q").focus
WebBrowser1.Document.All("q").Value = "blah blah"
WebBrowser1.Document.All("btng").focus
WebBrowser1.Document.activeElement.Click
```

Cheers...

----------


## Gaje21

i keep getting an Error 91 message. Anyone know why?

----------


## Gaje21

The codes here dont seem to be working for me. I can get the page loaded using:



```
Private Sub Command0_Click()

Dim webBrowser1 As WebBrowser

    Set webBrowser1 = New WebBrowser
    Set webBrowser1 = CreateObject("InternetExplorer.Application")
With webBrowser1
    .Navigate "http://www.ncl.com/edocs"
    .Visible = True

.Document.Forms(0).all("txtResID").focus
.Document.Forms(0).all("txtResID").Value = "blah blah"
End With
End Sub
```

but nothing fills in and i get the error 91 message the .Document.Forms(0) line

----------


## msgjp7

```
.Document.all("txtResID").focus
.Document.all("txtResID").Value = "blah blah"
```

Try making the following changes....

----------


## Gaje21

now i get an error that says "Runtime error -2147467259 (80004005) Autmation Error Unspecified Error)

----------


## msgjp7

```
Private Sub Form_Load()
WebBrowser1.Navigate "http://www.ncl.com/edocs"
End Sub

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)

With WebBrowser1
    .Document.Forms(0).All("txtResID").focus
    .Document.Forms(0).All("txtResID").Value = "blah blah"
End With

End Sub
```

This won't load IE but use the webbrowser control in the form.

----------


## Gaje21

That code tells me WebBrowser1 is not defined. Don't i need to dim it somewhere?

bwt - im using VB through MS Access.

----------


## msgjp7

Ahhhh..Ok. Let me think about this because my code works fine in VB. I tested it. 

Do you have access to the "microsoft internet control", ieframe.dll? If so, just add it to your project and that will be the end of it.

----------


## Gaje21

yes i have that added.

----------


## Gaje21

im using the microsoft internet control library, but its called "shdocvw.dll". What is "ieframe.dll"?

----------


## msgjp7

Let me try a few things in Access..

----------


## msgjp7

Sorry about the ieframe thing. You're right, it's shdocvw.dll.

----------


## Gaje21

thank you for helping me out with this. I've been going nuts for the past week trying to get this to work!

In Access i have a button that launchs this code OnClick (if that helps any).

----------


## msgjp7

Well..I'm new to Access 2007 (sometimes hard to figure where things are in a new version) and I don't see the internet control component and I've tried a few things but I can't seem to add it. So I have no way of helping you in Access.

My guess as to what your problem is that you're trying to access the text box before the page is fully loaded. Add the navigate command to the form_load part (get rid of it from the button click event). Once the page is fully loaded, click your button. Hope this helps.

----------


## Gaje21

in the VB editor: Tools > References > Microsoft Internet Controls.

i tried adding:



```
Do Until webBrowser1.Busy = False
Do Events
Loop
```

to make sure the page was fully loaded, but that doesnt work either.

----------


## msgjp7

I got that far but I can't actually add the component to the form. Were you able to actually add the component to your form? Are you using Access 2007?

----------


## Gaje21

im using Access 2003. To add it to the form, you just make sure the box next to it is checked, yes?

----------


## Gaje21

i definitely think my problem is that its not waiting for the browser to stop loading. 

if i add an If webBrowser1.Busy = False statement around my .document lines, i get no error, but at the same time it doesnt fill in the fields.

----------


## msgjp7

If I were using 2003 I wouldn't have any problems. Welcome to the World of 2007. If I figure it out I will post back..

----------


## Gaje21

ok thats definitely my problem. I found a sub ruitine that Pauses for given amount of time, so i made it pause for 10 seconds, and it works! 

Except, thats not a very reliable way of doing it in case the page takes a longer time to load for some reason. 

how can i just have it check that the page is done and completely loaded?

----------


## msgjp7

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)



```
With WebBrowser1
    .Document.Forms(0).All("txtResID").focus
    .Document.Forms(0).All("txtResID").Value = "blah blah"
End With

End Sub
```

FYI. My toolbox in Access is greyed out and I can't get to it..Seems like there's lots of others in my situation out there...

----------


## Gaje21

ok it definitely works now.

to make it wait i used:



```
Do Until webbrowser1.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
```

but now i need to figure how to click the "submit" button on the page. How do i go about that?

----------


## Gaje21

I'm trying to use the "Check if word/string is found on page" code on the first page of this thread, but keep getting an Error 91 message on this line:



```
For i = 1 To WebBrowser1.Document.All.length
```

First i got an object not defined error because "webBrowser1" wasnt Dim'd, so i dim'd it as "Dim webBrowser1 as webbrowser" but now i need to SET it to something - i just dont know what i SET it to. Anyone know?

----------


## dch31969

I realize this may sound odd...but can the Webbrowser Control be embedded in a HTML page? If so how would I do it? 

I'm building a Folder Home Page to replace my Outlook Today and would like to be able to use it as a file browser right on the page.

----------


## penagate

> I realize this may sound odd...but can the Webbrowser Control be embedded in a HTML page? If so how would I do it? 
> 
> I'm building a Folder Home Page to replace my Outlook Today and would like to be able to use it as a file browser right on the page.


Use an iframe element.

----------


## dch31969

> Use an iframe element.


Ok...I know how to put an iframe into a HTML page, but given that I had no idea until yesterday that the WebBrowser control existed, could you please provide me with the syntax? I should be able to figure things out from there.

----------


## penagate

sorry, I didn't mean embed the WebBrowser using an iframe, but just point the iframe to the directory you want to browse.

----------


## dch31969

> sorry, I didn't mean embed the WebBrowser using an iframe, but just point the iframe to the directory you want to browse.


So its not possible to present an Explorer like interface complete with folders, drives, files? I'm essentially looking give my users everything that they have when they explore their PCs.

----------


## MaJiStiC

That auto submit thing is good With WebBrowser but how do u find the exact Thing to be written like. If i do it on. http://login.yahoo.com Then if i view html code for this page i see Document.Write. So I write it like this

WebBrowser1.Document.Write.passwd.value = strpw

passwd is PASSWORD so it doesnt work  :Mad:

----------


## MaJiStiC

Nvm It Works Thanks For The Help By msgjp7

----------


## vali20

Hi, if you know, I need some codes! For the find box (when I start the find box and start searching a word, I want webbrowser to highlight it). I need codes for the right click menu, such as 'Save Picture As...'; 'E-mail Picture'; 'Print Picture'; 'Set as Background'; 'Set as Desktop Item'; 'Copy Shortcut'; 'Add to favorites'; 'Open link'; 'Open link in new window'; 'Save Target as...'; 'Print Target'. I want to know, if I have open form1, how to open a NEW form1 with a commandbutton? Please help with these problems!

----------


## akhileshbc

Is there any way to block pop ups.??? :Smilie:

----------


## EntityReborn

Here is my current code:


```
Option Explicit

Dim doc As HTMLDocument

Private Sub Command1_Click()
    WebBrowser1.Navigate "http://www.google.com"
End Sub

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    Dim i As Long, EHTML
    For i = 1 To WebBrowser1.Document.All.length
        Set EHTML = _
        WebBrowser1.Document.All.Item(i)

        If Not (EHTML Is Nothing) Then
            If InStr(1, EHTML.innerHTML, "Google", vbTextCompare) > 0 Then
                Replace EHTML.innerHTML, "Google", "Boogle"
            End If
        End If
    Next i
    doc = WebBrowser1.Document
End Sub
```

Basically, supposed to replace every Google string with Boogle. Works, as I tested with MsgBox, but the thing is EHTML doesnt writeback to the page, so EHTML is changed, while whats being displayed isn't. Any way to writeback the changes without reloading the page?

----------


## n3mesis125

> *Custom Right Click Menu*
> This is an example show how to make your own custom right click menu. in order for this to work you must add the "Must Add Microsoft HTML Object Library" to your refrance.Also make your own custom menu using the menu editor I named my "mnu"
> Please Note it will effect all the context menus in the webbrowser.
> 
> 
> VB Code:
> 'Must Add Microsoft HTML Object Library
Option Explicit
    Public WithEvents HTML As HTMLDocument
 Private Function HTML_oncontextmenu() As Boolean
   HTML_oncontextmenu = False
   PopupMenu mnu '<---Check the mnu to your own menu name
End Function
 Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
 Private Sub Form_Unload(Cancel As Integer)
   Set HTML = Nothing
End Sub
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, _
                                                 URL As Variant)
   Set HTML = WebBrowser1.Document
End Sub


Might be bringing an old post back alive but I definately needed help with this. The above code got me started on making my own context menu for the webbrowser control. However, My webbrowser control page that it navigates to has an iframe. When I right click on the iframe it does not keep the contextmenu, is there a way to fix this?

Thanks,
n3m.

----------


## jmsrickland

So, does you example work with IFrames?


Nevermind, I see now you stated that. BTW: I have been working on that problem from your other thread and so far no luck but I am sticking with it since I have learned a few things about frames and things since then so maybe, just maybe, I might be able to figure it iut.

----------


## dbuhid

Hi. Is there anyway any to get "updated" html code on pages with AJAX? Im working with .net 2008, Webbrowser. 
Is there any workarround to solve this? 
Thanks.
Ariel

----------


## JazzBass

Hi all,

Thanks for the control tips and examples.  I'm developing an Outlook-Addin in VB6 and I'm trying to do what is outlined in 'Making page on startup' as listed below.  I'm retriving HTML from a database and would like to display it in the webbrowser control.  



```
      Private Sub Form_Load()
          WebBrowser1.Navigate "about:blank"
      End Sub
      Private Sub Command1_Click()
          Dim HTML As String
              '----------The HTML CODE GOES FROM HERE AND DOWN----------
          HTML = "<HTML>" & _
                  "<TITLE>Page On Load</TITLE>" & _
                  "<BODY>" & _
                  "<FONT COLOR = BLUE>" & _
                  "This is a " & _
                  "<FONT SIZE = 5>" & _
                  "<B>" & _
                  "programmatically " & _
                  "</B>" & _
                  "</FONT SIZE>" & _
                  "made page" & _
                  "</FONT>" & _
                  "</BODY>" & _
                  "</HTML>"
                  '----------The HTML CODE GOES HERE AND ABOVE----------
          WebBrowser1.Document.Write HTML
      End Sub
```

The problem is that I have no intellisense past WebBrowser1.Document (no .Write). and when I add it, the program errors out.

I have a reference to the Microsoft Internet Controls, but I don't know what is the matter.

Any help would be appreciated.

Thanks,
JB

----------


## Xiphias3

Here's 2 additions: 
Requires MSHTML Object Library and the WebBrowser is called wbMain

*Waiting for a webpage to load*


```
cNavAndWait
```


vb Code:
Option Explicit Private Declare Function GetTickCount Lib "kernel32.dll" () As LongPrivate Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long) Private m_bDOMReady        As BooleanPrivate WithEvents m_ctlWB As WebBrowser Public Function navigateAndWait(ByVal ctlWebBrowser As WebBrowser, ByRef vData As Variant, Optional ByRef lMaxWaitTimeMillis As Long = 45000) As Boolean    On Error GoTo EH    Dim lEndTime As Long, obj As IHTMLElement, szURL As String        '--Navigate and wait for the web page to load    '--vData can be a string(url) or an HTML Object        Set m_ctlWB = ctlWebBrowser        If (IsObject(vData)) Then        Set obj = vData        Select Case UCase(obj.tagName)            '--Hyperlink reference, like links on a page            Case "A"                Call ctlWebBrowser.Navigate(obj.href)                        '--Forms, like login pages            Case "FORM"                Call obj.submit                            '--Something else, so try to click it            Case Else                Call obj.Click        End Select    Else        '--Regular URL        szURL = CStr(vData)        Call ctlWebBrowser.Navigate(szURL)    End If        lEndTime = (GetTickCount() + lMaxWaitTimeMillis)    m_bDOMReady = False    Do While (Not m_bDOMReady)        '--Check for timeout        If ((lMaxWaitTimeMillis <> -1) And (GetTickCount() > lEndTime)) Then Exit Do        '--So app doesnt freeze        DoEvents        '--Dont kill the CPU        Call Sleep(5)    Loop    If (Not m_bDOMReady) Then        Call m_ctlWB.Stop    End If    Set m_ctlWB = Nothing        navigateAndWait = (m_bDOMReady)    Exit Function    EH:    Call Err.Clear    navigateAndWait = FalseEnd Function Private Sub m_ctlWB_DocumentComplete(ByVal pDisp As Object, URL As Variant)    On Error GoTo EH    Dim oHTMLDoc As HTMLDocument        '--In pages with no frames, this event fires one time after loading is complete.    '--In pages where multiple frames are loaded, this event fires for each frame where the DWebBrowserEvents2::DownloadBegin event has fired.    '--The top-level frame fires the DocumentComplete in the end.    '--So, to check if a page is done downloading, you need to check if the IDispatch* parameter, is same as the IDispatch of the WebBrowser control.        If (pDisp Is m_ctlWB.object) Then        m_bDOMReady = True    ElseIf (TypeOf pDisp.Container Is HTMLDocument) Then        Set oHTMLDoc = pDisp.Container        If (oHTMLDoc.frames.length = 0) Then            m_bDOMReady = True        End If    End If    Exit Sub    EH: Call Err.ClearEnd Sub

Example:

vb Code:
Private Sub cmdGo_Click()    Dim oNAW As cNavAndWait, sStart As Single        Set oNAW = New cNavAndWait    sStart = Timer()    Call oNAW.navigateAndWait(wbMain, txtURL.Text)    Call MsgBox(txtURL.Text + " took " + CStr(Timer() - sStart) + " seconds to load.", vbOKOnly Or vbInformation, "Navigate And Wait")    Set oNAW = NothingEnd Sub




*How to copy and save an image from a webpage*

vb Code:
Option Explicit Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long) Private m_bDOMRdy As Boolean Private Sub cmdCopy_Click()    Dim pDoc As HTMLDocument, pImgEle As IHTMLImgElement, pCR As IHTMLControlRange, szImgname As String        '--Grab the image of the first picture on the page and copy it into the PictureBox    Set pDoc = wbMain.Document    For Each pImgEle In pDoc.All.tags("IMG")        szImgname = Mid(pImgEle.src, InStrRev(pImgEle.src, "/") + 1)                '--Create a control range        '--MSDN: Contains a range of control type elements that is used for control selection; _                 and represents an array of controls that can be operated on as a group.        Set pCR = pDoc.body.createControlRange()        '--Clear the clipboard        Call Clipboard.Clear        '--Add the image element        Call pCR.Add(pImgEle)        '--Copy it to the clipboard        Call pCR.execCommand("copy")        '--Do what you want with the image since its on the clipboard        Set pbPic.Picture = Clipboard.GetData(vbCFBitmap)        '--Save the image        Call SavePicture(pbPic.Picture, "C:\" + szImgname)                Exit For    Next pImgEleEnd Sub Private Sub Form_Load()    m_bDOMRdy = False    Call wbMain.Navigate("http://frontrowcrew.com/")    Do While (Not m_bDOMRdy)        DoEvents        Call Sleep(10)    LoopEnd Sub Private Sub wbMain_DocumentComplete(ByVal pDisp As Object, URL As Variant)    If (pDisp Is wbMain.Object) Then        m_bDOMRdy = True    End IfEnd Sub

----------


## ts96

How can I make my webbrowser remember any password and username i enter?

----------


## jmsrickland

What do you mean by webbrowser? Are you talking about an application webbrowser like IE or FireFox or are you talking about the webbrowser control that you use in a VB program? If it's the control you do not make it remember passwords/usernames. This you must do yourself with some sort of external file or database.

----------


## ts96

I mean the webbrowser control. I can save my passwords in a file, but how can I make the WebBrowser control detect when I login to a page??

----------


## jmsrickland

You can't in the strict sense of making the browser detect the login. You need to control the page that you are logging into in you VB program. By using the DocumentComplete event of the WebBrowser control you can determine if the current document (or page) is the login page. You have to be familiar with this page (i.e. you need to know it's URL and the names of the fields on the page that are used to enter the username and passwords). Once you know you have this page loaded and the names of the two fields you simply copy the username and password from your file into these two fields and then you must also know the name of the submit button so you can programmaticly "click" on the submit button.

Let's say, for example, I want to automate a login to a website. In an external file I would keep the usernames and passwords. Now let's also say I know exactly the URL of the page that has the username and password fields on it and also the login button. So, for this example, the URL of the page is "http://www.jmswebsite.com/loginpage" and the names of the fields on this page are "userID" and "pass" for the username and password and "login" for the submit button.    

Here is a very simple code example of the above.


```
Private Sub WebBrowser_DocumentComplete(ByVal pDisp As Object, URL As Variant)
  '
  '
 If URL = "http://www.jmswebsite.com/loginpage" Then 
   WebBrowser.Document.All("userID").Value = username from your external file
   WebBrowser.Document.All("pass").Value = password from your external file

   WebBrowser.Document.All("login").Click
 End If
   '
   '
End Sub
```

This example may not exactly solve your problem but it shows the very basics of one way you might approach your problem.

----------


## ts96

You helped me a lot. Thank you. If I manage to solve my problem I will post the code here!!!

----------


## ts96

Now I have another question. I can't explain it in words but I will show you an exampple:
I have  http://www.vbforums.com/showthread.php?t=384076&page=3 and I want to have this: http://www.vbforums.com/ . How can I do this?? (I want it for the favicon)

----------


## le_taon

You can use small tip:

vb Code:
Private Sub Form_Load()    WebBrowser1.Navigate "http://www.vbforums.com/showthread.php?t=384076&page=3"End SubPrivate Sub WebBrowser1_DownloadComplete()    Dim i As Integer    Dim SearchString    Text1.Text = WebBrowser1.LocationURL    SearchString = Text1.Text  ' String to search in.    SearchChar = ".com" ' Search for "Xp".    i = InStrRev(SearchString, SearchChar, , 1) 'InstrRev(stringcheck, stringmatch[, start[, compare]])    Text2.Text = Left(Text1.Text, (i + 3))End Sub

----------


## jeffrey4u

i tried the 'Custom Right Click Menu' side of the tutorial 
but is not working and i don't know why. 
am using windows Vista, has it got something to do with it.

----------


## hamzasoft

my Question is 
how can i copy image in web browser control programatically
for example web page which i have loaded into web browser control have got 5 images and if i can right click on each image and save it is alowing me to do it manually but i want to do this autometacally
and i just want to save one image from the page may be this is first image or mid image or last image

----------


## ndondo

how to control the download window
say we browse to http://go.microsoft.com/?linkid=9729747

then it will come up with a save file prompt
we save it 

so I want to be able to see if the download is finish or not.. 

thank you

----------


## thechazm

This is a great post! I have a specific question a little on the advanced side of this topic. I am trying to save "specific" data from the website to tables in access. Here is a small portion of the web site I am dealing with.



```
<div class="details">
	<span id="Quals" onclick="javascript: toggleTable(this.id)" class="OutlineIcon">
	<img id="imgQuals" src="images/minusIcon.gif" border="0" WIDTH="14" HEIGHT="14"></span>
	<span class="detailsHd">ATMS Quals</span>
	
	<table id="tblQuals" border="1" cellpadding="2" cellspacing="0" class="details">
	
		<tr><th>Qual Number</th>
			<th>Title</th>
			<th>Expires</th></tr>
		
		
		<tr><td align="left" valign="top" class="Normal">
				ADM_MAT&nbsp;</td>
			<td align="left" valign="top" class="Normal">
				<a href="atms_supv_qualtree.cfm;jsessionid=0e30e09a3ccb91f2c5ca5e806e7d2b2d6176?PID=22644&amp;qualcat=ADM&amp;qualid=_MAT&amp;title=MANDATORY ANNUAL TRAINING" class="Normal">MANDATORY ANNUAL TRAINING&nbsp;</a></td>
			<td align="center" valign="top" class="Normal">
				10/31/2011&nbsp;</td></tr>
		
		
		<tr><td align="left" valign="top" class="Normal">
				BASSHIP_WORKER&nbsp;</td>
			<td align="left" valign="top" class="Normal">
				<a href="atms_supv_qualtree.cfm;jsessionid=0e30e09a3ccb91f2c5ca5e806e7d2b2d6176?PID=22860&amp;qualcat=BAS&amp;qualid=SHIP_WORKER&amp;title=BASIC SHIPBOARD WORKER" class="Normal">BASIC SHIPBOARD WORKER&nbsp;</a></td>
			<td align="center" valign="top" class="Normal">
				10/31/2011&nbsp;</td></tr>
		
		
		<tr><td align="left" valign="top" class="Normal">
				BASSHOP_WORKER&nbsp;</td>
			<td align="left" valign="top" class="Normal">
				<a href="atms_supv_qualtree.cfm;jsessionid=0e30e09a3ccb91f2c5ca5e806e7d2b2d6176?PID=22861&amp;qualcat=BAS&amp;qualid=SHOP_WORKER&amp;title=BASIC SHOP WORKER" class="Normal">BASIC SHOP WORKER&nbsp;</a></td>
			<td align="center" valign="top" class="Normal">
				10/31/2011&nbsp;</td></tr>
```

I am currently pulling the data using the website control and using this code here to put it into a string but have no idea which way to go now...



```
Dim teststring As String

teststring = WebBrowser1.Document.body.innerhtml
```

Thanks all

----------


## akhileshbc

@thechazm: For gathering data from table (of HTML), *dilenette* had posted a sample code that uses ADO to retrieve the information. If you search the forum, you'll find that code.  :wave:

----------


## thechazm

Thank you for pointing me in the right direction. The name you referenced though does not seem to be listed in the user directory so I'm just scanning the net now.

Have a good one,

TheChazm

----------


## CDRIVE

That's because his handle is spelled  *dilettante*

----------


## akhileshbc

> Thank you for pointing me in the right direction. The name you referenced though does not seem to be listed in the user directory so I'm just scanning the net now.
> 
> Have a good one,
> 
> TheChazm





> That's because his handle is spelled  *dilettante*


Oops...  :Big Grin:  Sorry guys.. Spelling mistakes.. :Stick Out Tongue:

----------


## thechazm

Thanks again. I was able to figure out what I needed by reading http://www.devarticles.com/c/a/HTML/...s-a-Recordset/

I will go read what dilettante posted to maybe get more in depth information but the code was as simple as this:


```
AtmsQualsNumber = WebBrowser1.Document.getelementbyid("tblQuals").rows(AtmsQualsc).cells(AtmsQualscc).innertext
```

Thanks again so very much for the responces and help,

TheChazm

----------


## NomiRao

and how can i get text from webbrowser to my form in vb6

----------


## thechazm

After a very long time of spending working with the webbrowser control I have learned quite a bit as far as how to make it work. Now I think I have hit another stump. I am trying to read a table with no id on a page. The page only has one table on it but I cannot seem to get the code to pickup on it. Any suggestions?

Here is what I have so far:


```
AtmsQualsLength = WebBrowser1.Document.getElementsByTagName("table").rows.length
```

And I have also tried:


```
AtmsCoursesLength = WebBrowser1.Document.getelementbyid("table").rows.length - 1
```

The reason why I am putting table as the table name is because of this post
http://www.eggheadcafe.com/software/...lass-name.aspx

Thanks to all

----------


## thechazm

Well I was not able to ever find a good solution for reading a table with no ID instead I used the instr function and with some calculations read the data from its source code. Its a pain and if the format changes then I would have to update the code but here is what I have.



```
'// Locate and assign Pay Shop
    lngSupCode = InStr(WebBrowser1.Document.documentelement.innerhtml, "Pay Shop")
    lngSupCode = lngSupCode + 210
    strBuildData = Mid(WebBrowser1.Document.documentelement.innerhtml, lngSupCode)
    lngSupCode = InStr(strBuildData, "&nbsp;")
    strBuildData = Left(strBuildData, lngSupCode)
    strBuildData = Mid(strBuildData, 18)
    lngSupCode = InStr(strBuildData, "&") - 1
    strBuildData = Left(strBuildData, lngSupCode)
    strPayShop = strBuildData
    
    '// Locate and assign Assn'd Shop
    lngSupCode = InStr(WebBrowser1.Document.documentelement.innerhtml, "Assn'd Shop")
    lngSupCode = lngSupCode + 210
    strBuildData = Mid(WebBrowser1.Document.documentelement.innerhtml, lngSupCode)
    lngSupCode = InStr(strBuildData, "&nbsp;")
    strBuildData = Left(strBuildData, lngSupCode)
    strBuildData = Mid(strBuildData, 14)
    lngSupCode = InStr(strBuildData, "&") - 1
    strBuildData = Left(strBuildData, lngSupCode)
    strAssignedShop = strBuildData
    
    '// Locate and assign Supv.
    lngSupCode = InStr(WebBrowser1.Document.documentelement.innerhtml, "Supv.")
    lngSupCode = lngSupCode + 200
    strBuildData = Mid(WebBrowser1.Document.documentelement.innerhtml, lngSupCode)
    lngSupCode = InStr(strBuildData, "&nbsp;")
    strBuildData = Left(strBuildData, lngSupCode)
    strBuildData = Mid(strBuildData, 16)
    lngSupCode = InStr(strBuildData, "&") - 1
    strBuildData = Left(strBuildData, lngSupCode)
    strSupCode = strBuildData
    
    '// Locate and assign Shift
    lngSupCode = InStr(WebBrowser1.Document.documentelement.innerhtml, "Shift")
    lngSupCode = lngSupCode + 200
    strBuildData = Mid(WebBrowser1.Document.documentelement.innerhtml, lngSupCode)
    lngSupCode = InStr(strBuildData, "&nbsp;")
    strBuildData = Left(strBuildData, lngSupCode)
    strBuildData = Mid(strBuildData, 14)
    lngSupCode = InStr(strBuildData, "&") - 1
    strBuildData = Left(strBuildData, lngSupCode)
    strShift = strBuildData
```

I just wanted to share what I have done so hopefully its usefull to someone.

Thanks,

TheChazm

----------


## ketanchauhan

how to set Page size for this control
and
how to set Page orientation  L/p
i have use this control as  Report Viewer in my application 

some report on Landscape and some Portrait 
some page A4 and Some Legal

Please Help Me

----------


## CDRIVE

> how to set Page size for this control
> and
> how to set Page orientation  L/p
> i have use this control as  Report Viewer in my application 
> 
> some report on Landscape and some Portrait 
> some page A4 and Some Legal
> 
> Please Help Me


The WB control conforms to the same properties as all other visible VB controls, IE, Top, Left, Height and Width. You can write code to change it at will.

----------


## ketanchauhan

> The WB control conforms to the same properties as all other visible VB controls, IE, Top, Left, Height and Width. You can write code to change it at will.


i want change Pagesize not top,left 
i want change  page oriantation landscape, portrait Please Tell me how we can change this ???

----------


## CDRIVE

> i want change Pagesize not top,left 
> i want change  page oriantation landscape, portrait Please Tell me how we can change this ???


That would be the Height and Width properties.

----------


## ketanchauhan

> That would be the Height and Width properties.


I Try But Problem Not Solved

----------


## jmsrickland

WebBrowser control does not have a landscape/portrait setting. You change the width and height of the control to the size you want. 

.Width = 8.5 and .Height = 11 will give you portrait whereas .Width = 11 and .Height = 8.5 will give you landscape. Just like CDRIVE told you in post #103. What else do you want?

----------


## ketanchauhan

> WebBrowser control does not have a landscape/portrait setting. You change the width and height of the control to the size you want. 
> 
> .Width = 8.5 and .Height = 11 will give you portrait whereas .Width = 11 and .Height = 8.5 will give you landscape. Just like CDRIVE told you in post #103. What else do you want?


i want to print landscape/portrait and page size a4,legal is it possible i check about this on msdn its display you can change from ScriptX

----------


## fotonut

I am trying to learn the DOM rather than doing what I have done in the past, parsing out an entire HTML page.   I don't seem to "get" the DOM for some reason.

I am attempting to use the example here but I can't seem to find the "alt=xxxx" values within the AnchorElement.

I am using this block of code above from this thread:


```
 Option Explicit
    Private Sub Form_Load()
        WebBrowser1.Navigate "www.vbforums.com"
    End Sub
    Private Sub WebBrowser1_DownloadComplete()
        'you must add the "Microsoft HTML Object Library"!!!!!!!!!
        Dim HTMLdoc As HTMLDocument
            Dim HTMLlinks As HTMLAnchorElement
                Dim STRtxt As String
        ' List the links.
        On Error Resume Next
            Set HTMLdoc = WebBrowser1.Document
                For Each HTMLlinks In HTMLdoc.links
                    STRtxt = STRtxt & HTMLlinks.href & vbCrLf
                Next HTMLlinks
            Text1.Text = STRtxt
    End Sub
```

The code above finds all the "href" info from all the links like this in the document, but how do I programatically find what the "alt" value is that is associated with these links?   There is no supported attribute for "alt" that I can find, i.e. HTMLlinks.alt <<< INVALID

Here is the HTML snipit that HTMLlinks.href finds.  I need to know the alt=xxx value associated with it:



```
<a href="main.php?g2_itemId=28"><img src="main.php?g2_view=core.DownloadItem&amp;g2_itemId=68&amp;g2_serialNumber=2" width="200" height="86" id="IFid1" class="ImageFrame_none giThumbnail" alt="Pyramids"/></a>
```


Thanks!

----------


## fotonut

I have a very large photo gallery on a system where the DB got corrupted.  Good news is I can view my old gallery but I just can't add anything to it.  I have recreated a second image of it on another URL with all the photos but no descriptions of any of them.  I need to copy over the descriptions.  I am currently trying to use Webbrowser control to copy all the text from the corrupt gallery to the new gallery.

I have a Webbrowser1 and Webbrowser2 session set up with the 2 screens I want to copy from and to.  I would like to learn to do this in the browser control rather than copy/paste if possible, but I will ultimately take advise on anything that works.

There are around 36 input fields to copy on each page but they exist as 2 types with different names.  Here are the 2 types:

Copy from/to Field type 1:


```
<input type="text" id="summary_130" size="60"
name="g2_form[items][130][summary]" value="The road to Alaska was a long and hard one.l"/>
<h4> Keywords </h4>
```

Copy from/to Field type 2:


```
<textarea id="description_129" rows="4" cols="60"
name="g2_form[items][129][description]">Land travel to Alaska is a long and challenging task for anyone to undertake.</textarea>
```

Of course my code will use the item numbers in the brackets [129], [130] etc to identify what goes where but how do I get started with a browser control to copy and paste from these two types of fields, an Input "value" and a textarea data-string?

Thanks!

----------


## Dsum

Did you ever find an answer to this question?? I have a similar issue.
I would like to get information from an html table that looks like this.

<tr class="vcard">
<td style="border-bottom: 1px solid gray"> &nbsp;</td>
<td style="border-bottom: 1px solid gray"><span class="tel">(###) ###-####</span> &nbsp;</td>
<td style="border-bottom: 1px solid gray"><br><strong><span class="fn org">ANY Insurance Agency</span></strong><br>
<span class="adr">
<span class="street-address">Any Address</span><br>
<span class="locality">ThisState</span><br>
<span class="region">MO</abbr>
</span>
</td>
<td style="border-bottom: 1px solid gray"> &nbsp;</td>
</tr>


This is more html code but im only trying to access "fn", "tel", "fn org",
"street-address","locality", and"region". 

Here are so facts i know. They list the agents info under a vcard element. Under that element there are name, tel, and orgainize listed. Then the address information is listed under the element "adr".  So i need to loop throught the information getting each set of agent information

----------


## fotonut

It's a catch 22; if you understood this stuff well enough to code in it, then you wouldn't be coding in it ;-)

I still don't grasp the DOM myself but being a lame hacker who codes mostly by example, this helped me a lot.   It sort of enumerates most of the major parts of the DOM.   I have altered my own version of it in fact with about 3 more screens and a verbose log file that even borders on being unreadable since it doubles down on so many example calls to the DOM.  I use it as a shell to go to the website I plan to manipulate and find what I am looking for and go from there.

I am not saying this will work for you, but for the most part I just run this, peruse through the output until I find what I am looking on one of the display output panels and then "cheat" by locating the VB code that produces the shortest path to accessing the info you are searching for.

If you are into bass-ackwards coding like me, maybe this will help get you started:
http://vb-helper.com/howto_get_webbrowser_text.html

----------


## fotonut

Also don't make the same "first mistake" I made by thinking that if you log into a session manually with IE that your VB browser control session code testing will automatically be logged in too just because you have open an active conventional IE user session with the same website.  They are separate and you will have to code any log-in sequence into your routine as well.

----------


## solo.mero

i love u all  :Stick Out Tongue:

----------


## Shohag_ifas

hi, is it possible do determine  whether a text (SPAN element) text is visible or not?

i tried:
body.parentElement.innerText
body.parentElement.outerText

even i manually select all (Ctrl+A) then paste into a text box and still that text (text is "invalid captcha warning" exits. but not visible in the control/browser.. 

but i need to get is it visible or not to track if user put correct cpathca or wrong.. 

i hope i a clear and waiting for someones help...

best regards
kamrul Hassan

----------


## DavidRemotti

this thread has been very useful, many thanks !
But I still have some problems.
My application is very simple: to prepare a series of map printout from Google Maps, for a list of points I have in a DB.
So I loop through the point, send the correct address to google maps and get the image on the webbrowser object in my form. Then issue the print command using pdf creator as printer.
The problem is that I would like to launch the procedure and get all the printout, but at now I must have put a msgbox after each point; without it the printout are empty, because the print command does not wait for the page to complete.
May someone give ne a hint ?
thx
David

----------


## coolcurrent4u

Can anyone help on how to simulate typing, which is a combination of onkeydown, onkeypress and onkeyup events? 

 regards

----------


## Nickie_Girl

> this thread has been very useful, many thanks !
> But I still have some problems.
> My application is very simple: to prepare a series of map printout from Google Maps, for a list of points I have in a DB.
> So I loop through the point, send the correct address to google maps and get the image on the webbrowser object in my form. Then issue the print command using pdf creator as printer.
> The problem is that I would like to launch the procedure and get all the printout, but at now I must have put a msgbox after each point; without it the printout are empty, because the print command does not wait for the page to complete.
> May someone give ne a hint ?
> thx
> David


You can delay the image print by having the script wait for the page to load.



```
Do Until webbrowser1.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
```

This should do the trick for you.

----------


## bilbo69

Hello,
I'm trying to write a simple routine that write a text in the page http://tinywebdb.appspot.com/storeavalue and press the button "Store a value".

Looking the html source of the page, the name of the first field il "*Tag*", the name of the second field is "*Value*" and the name of the button is "*fmt*"

My test code is

    WebBrowser.Document.All("Tag").focus
    WebBrowser.Document.All("Tag").Value = "xxxxxx"

    WebBrowser.Document.All("Value").focus
    WebBrowser.Document.All("Value").Value = "yyyyyy" 

    WebBrowser.Document.All("fmt").Click

but nothing happen on the last row (don't click)
Any idea?
Thank you, Gianluca

----------


## deepakpc007

How can i get the url of the site that is going to get navigated?Is there a property of webrowser for it?
Thanx in advance..

----------


## riov

Is "Disabling functions appropriately" code on the first page supposed to disable CTRL+P? If so, it does not.
Is there a third way of disabling CTRL+P besides hooking keyboard or using WBCustomizer.dll?

----------


## naseeh

Checkbox in a page, how to control it

in the website, the checkbox i wanna check, the code is like this
<input type="checkbox" onchange="groupCheck(this.checked)">

and from your guide, WebBrowser1.Document.GetElementById("PersistentCookie")*.Checked* = True 'checked 
that i cant find, help me out with this, i'm using visual studio 2008

----------


## VbSinan

I am posting html data with web form.. and i check my web page.. i dont see the iframe codes.. why wb component replacing iframe codes?

----------


## llxx_lord_xxll

Is there any way to changing WebBrowser Document Location without navigating?

Actually i want to make a browsing control with socket connection, Because i have many Forms Data to submit directly through links.

I use to navigate about**:blank on form_load event. But the images are not showing because of browser location is "about**:blank"

I need to change it to my specific location. I've tried by adding base url in <head> tag when the source is loading but that didn't work.

----------


## lemario

Hello. Im using VB.net. I need a way of getting the awebsite favicon. Can you help?

----------


## CDRIVE

I would suggest posting your query to the NET section of the forum.

----------


## zeniitti

I have a question, maybe this is the wrong thread...

I have a little "Windows Form1" and it has very basic WebBrowser made with Studio Community 2013. WebBrowser is fills the whole Form1. If I give it a static url in WebBrowser properties, it navigates to that address no problem. Is is possible to make it navigate something like variable that is given when calling this Form1.exe from CMD example?

My idea is that normally when you call that exe it will open the window and navigate to www.google.fi for example. But if I call it for exampl "Form1.exe www.bing.com" or "Form1.exe -p1www.bing.com" or something like that, it would open the window and navigate to www.bing.com.

This should be possible but how? I'm new using Studio and at has been a while when I coded these applicatios...

Thanks!

----------


## Arnoutdv

Then you are using VB.NET, this section is dedicated to VB6 and older.
So ask your question in a new thread in the correct forum.

----------


## teamster

Animated Browser Complete:

2 images: 1 The animation Gif. 2 The Still Image. I use these 

Set the visible property to False and stage them one on top of the other around the URL textbox.

I named the PictureBox of each to "Complete" for the still image, and "Loading" for the animated gif.

Then Under document complete I have this code.



```
    Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        Loading.Visible = False
        Complete.Visible = True
    End Sub
```

Then when ever I navigate, go forward, go back, refresh I have this code.



```
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'This is the GO button.
        WebBrowser1.Navigate(TextBoxURL.Text)
        Loading.Visible = True
        Complete.Visible = False
    End Sub

    Private Sub Button13_Click(sender As System.Object, e As System.EventArgs) Handles Button13.Click
        'This is the FORWARD button
        WebBrowser1.GoForward()
        Loading.Visible = True
        Complete.Visible = False
    End Sub

    Private Sub Button12_Click(sender As System.Object, e As System.EventArgs) Handles Button12.Click
        'This is the BACK button
        WebBrowser1.GoBack()
        Loading.Visible = True
        Complete.Visible = False
    End Sub

    Private Sub Button11_Click(sender As System.Object, e As System.EventArgs) Handles Button11.Click
        'This is the REFRESH button
        WebBrowser1.Refresh()
        Loading.Visible = True
        Complete.Visible = False
    End Sub
```

Now you have animated your navigation and can stop wondering if your click on the button took or not.

Disclaimer: Though this code is in VB2010, I am sure the same principle can be used in older compilers.

----------


## AAraya

I'm using the browser control to display html code I generate myself.  I want to display a link which doesn't actually navigate anywhere (the link is not for navigation, it's to trigger an action.) and I want to know when the user clicks on the link.  How is this achieved?

two questions:

1. how do I create a hyperlink like this - e.g. Click here to do such and such...  
2. Is an event raised somewhere when the link is clicked on by the user?  I don't want the browser to automatically navigate anywhere when the user clicks on the link.  I want to take some other action in my app when the user clicks on the link.  

TIA,
Art

----------


## DEXWERX

you should post in a new thread.
There's many ways - but the most obvious is something like this.




```
<div id='DoSomething' style='text-decoration: underline; cursor:pointer;'>A Link!</div>
```



```
Private WithEvents MyDiv As HTMLDivElement

Private Function MyDiv_onclick() As Boolean
    MsgBox "Div Clicked!"
End Function

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    Set MyDiv = WebBrowser1.Document.getElementById("DoSomething")
End Sub
```

----------


## AAraya

> you should post in a new thread.
> There's many ways - but the most obvious is something like this.


Thanks Dex, very helpful of you!  

As a follow question to your suggested solution.  The Div always appears as a new line.  Is there a way to have it stay on the current line and not start a new line?

----------


## AAraya

I spent days searching this one out so it may be of help to someone else.

*Change the border style from 3d to flat:*



```
Private Sub WebBrowser_NavigateComplete2(ByVal pDisp As Object, URL As Variant)
    WebBrowser.Document.Body.style.border = "none"
End Sub
```

----------


## AAraya

The Custom Right Click Menu code also seems to work as an alternate way to disable the context menu without requiring subclassing or use of a helper DLL like your earlier solution outlines.  Simply use the custom right click menu code you have but omit the line which shows a custom popup menu.



```
'Must Add Microsoft HTML Object Library
Option Explicit
    Public WithEvents HTML As HTMLDocument
 
Private Function HTML_oncontextmenu() As Boolean
   HTML_oncontextmenu = False
End Function
 
Private Sub Form_Load()
    WebBrowser1.Navigate "www.google.com"
End Sub
 
Private Sub Form_Unload(Cancel As Integer)
   Set HTML = Nothing
End Sub
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, _
                                                 URL As Variant)
   Set HTML = WebBrowser1.Document
End Sub
```

----------


## Barcrest

Does anyone know what the extra arguments do when using navigate?

----------


## neil00

*Loading HTML content into a WebBrowser control from memory*

Works with SVG+XML loading.

_References :
"Loading HTML content into a WebBrowser control from memory", Scott Waletzko (sp!ke), link"Loading HTML content from a Stream", MSDN, link"[VB6] Modern Shell Interface Type Library - oleexp.tlb - VBForums", fafalone, link
_

On VB6 IDE, add the following references :
_Microsoft HTML Object Library__OLEXP - olelib With Modern Interfaces by fafalone, v4.x_
and of course _Microsoft Internet Controls_ component.



```
Private Declare Function CreateStreamOnHGlobal Lib "ole32.dll" (ByRef hGlobal as Any, ByVal fDeleteOnResume as long, ByRef ppstr As Any) As Long

Public Sub loadContent(ByRef wb As SHDocVwCtl.WebBrowser, ByRef htmlDoc as MSHTML.HTMLDocument, ByRef aContents() as Byte)
Dim oPersistStreamInit as IPersistStreamInit
Dim oStream as IStream
' ensure the document is loaded
wb.Navigate2 "about:blank"
While wb.ReadyState <> SHDocVwCtl.tagREADYSTATE.READYSTATE_COMPLETE
DoEventsWend

' get a reference to the document
Set htmlDoc = wb.Document

' initialize the document using the IPersistStreamInit
Set oPersistStreamInit = htmlDoc
oPersistStreamInit.InitNew

' set the content into a stream
If Not CreateStreamOnHGlobal (aContents(0), True, oStream) Then
' load the content into browser
oPersistStreamInit.Load oStreamEnd If

Set oStream = Nothing
Set oPersistStreamInit = NothingEnd Sub
```

----------

