VB6 - WebBrowser Detect if a link has been clicked - vba

Hi I am new to Visual Basic 6,
My application has a section which shows an advertisement. When the ad is clicked, the button "Power" is activated.
I tried to detect click on my ad that is inside a with the id "anuncio1".
So far I've only managed to detect when you click in the WebBrowser zone but does not detect when I've clicked on a link.
Then I let my code:
Option Explicit
'Reference to HTML DOM
Dim WithEvents HTMLDOC As HTMLDocument
Private Const READYSTATE_COMPLETE As Long = 4
'Load the website directly to the ad hiding Scrollbars and focusing anchor #anuncio1
Private Sub Form_Load()
WebBrowser1.Navigate "www.traductoramixer.es#anuncio1"
Do While WebBrowser1.Busy: DoEvents: Loop
Do While WebBrowser1.ReadyState <> READYSTATE_COMPLETE: DoEvents: Loop
WebBrowser1.Document.parentWindow.scrollBy 25, 0
WebBrowser1.Document.body.Scroll = "no"
WebBrowser1.Document.body.Style.overflow = "hidden"
End Sub
'Deteck click in WebBrowser1 zone
Private Function HTMLDOC_onclick() As Boolean
Command1.Enabled = True
End Function
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If Not WebBrowser1.Document Is Nothing Then
Set HTMLDOC = WebBrowser1.Document
End If
End Sub

i suggest you:
1) create a Timer with Interval 100
2) and check WebBrowser1.LocationName string value frequently
if its value was not equal to the url your customer clicked on it, then be sure that your customer clicked on a wrong link

Related

Handle HTMLElement events in VBA

I use SHDocVw.InternetExplorer to show in powerpoint a local html file to the user. The file contains a form with a submit button and I would like to run my vba function when the button is clicked. I did the following to handle the onQuit-event of the InternetExplorer.
Class module "CIE"
Public WithEvents ie As SHDocVw.InternetExplorer
Private Sub ie_onQuit()
Debug.Print "onQuit was fired"
End Sub
Module code
Option Explicit
Public curCIE As CIE
Sub open_ie()
Dim CIEobj As CIE
Set CIEobj = New CIE
Dim ie As SHDocVw.InternetExplorer
Set ie = New SHDocVw.InternetExplorer
ie.Visible = True
ie.Navigate "C:\search.html"
Do While ie.Busy Or ie.readyState <> 4
DoEvents
Loop
Set CIEobj.ie = ie
Set curCIE = CIEobj
End Sub
I actually want to handle the onclick event of
curCIE.ie.Document.getElementsByTagName("button").Item(0)
but I do not know how to proceed.
You could add reference to MSHTML, then make your class module this way:
Public WithEvents ie As SHDocVw.InternetExplorer
Private WithEvents button As MSHTML.HTMLButtonElement
Public Sub LoadButton()
Set button = ie.document.getElementsByTagName("button").Item(0)
End Sub
Private Function button_onclick() As Boolean
'do what you want here
End Function
Private Sub ie_onQuit()
Debug.Print "onQuit was fired"
End Sub
And then, in the other module, add this statement after setting CIEobj.ie property:
CIEobj.LoadButton

Find value stored in IE object in VBA

I have declared an object named IE in my VBA code.
Set IE = CreateObject("InternetExplorer.Application")
Sometimes user may close the browser linked to IE object. How can i write code to find if the browser is closed or open?
As shown in below image, software shows Internet Explorer when i place cursor on IE object during run time. Can this value be used to determine if browser is closed or open? If not, any other way?
Create a custom class to capture the Internet Explorer events using WithEvents. You'll need to set a reference to Microsoft Internet Controls.
Option Explicit
Private WithEvents IE As InternetExplorer
Private Sub IE_OnQuit()
End Sub
Private Sub IE_OnVisible(ByVal Visible As Boolean)
End Sub
Private Sub Class_Initialize()
Set IE = New InternetExplorer
End Sub
If the object is closed, then accessing some of it's members should give you an error.
Dim isOpen As Boolean ' False by default
On Error Resume Next
If IE.HWND > 0 Then isOpen = True
On Error Goto 0

Change rendered HTML in vba WebBrowser control

I have an Access 2010 Form with a WebBrowser control that I would like to remove a Submit button from the rendered HTML. My WebBrowser control works fine when I'm reading the HTML but I get an error when trying to change what's rendered. I've tried several methods and they all return an "Object Required" error. I have a lot of working code that uses the WebBrowser control so I'm hesitant to change it out for another control. Is there anyway of doing this with this control?
Below is a snippet of the latest code:
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
Dim strLook As String
Dim doc As HTMLDocument
Set doc = WebBrowser1.Document
Dim txtInner
strLook = "<input type=""submit"" name=""subaction"" value=""Force"" class=""inputfield"">"
txtInner = WebBrowser1.Document.Body.innerHTML
txtInner = Replace(txtInner, strLook, "")
Webrowser1.Document.Body.innerHTML = txtInner
End Sub
Thanks in advance!
Something like:
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
Dim doc As HTMLDocument
Dim els
Set doc = WebBrowser1.Document
Set els = doc.getElementsByTagname("input")
For Each el In els
If el.Value = "Force" And el.className = "inputfield" Then
el.ParentNode.RemoveChild el
Exit For
End If
Next el
End Sub

Do Action if user returns to Excel from another Application

I have an Excel workbook that has links to a webpage. The user can click on the links, which minimize the Excel window and open their browser. When they are done with the site, they minimize or close their browser, which returns them to Excel (as it was their previous active window).
I would like VBA to take an action (update a table) when the user is returned to Excel.
I've looked at the Workbook_WindowActivate event, but this only works if you are moving from one Excel Workbook to another within the Excel Application.
Maybe I could use Application.name or the Windows function GetActiveWindow somehow but I am not sure how best to do this.
Any ideas? Thanks!
You want to add an event handler for Workbook_SheetFollowHyperlink. You can then use the code below. This just checks to see if the webpage has focus. the ' DO EVENTS ' is where you would add your code and then exit the sub
'********************* References used
'* Microsoft Shell Controls An Automation : shell32.dll*
'* Microsoft HTML Objects Library: MSHTML.dll expand ยป *
'* Microsoft Internet Controls: IEFRAME.dll *
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim ie As InternetExplorer 'IE window variable
Dim sUrl 'url of the webpage
Dim dt As Date 'timer
'set the url to look for
sUrl = Target.Address
'set initial timeout period *used instead of browser ready due to page redirection.
'you should also check the browser ready status
dt = DateAdd("s", 5, DateTime.Now)
Do While dt > DateTime.Now
DoEvents
Loop
'reset the timeout period to allow time to view and select
dt = DateAdd("s", 30, DateTime.Now)
Dim shShell As New Shell ' windows shell variable
'continue loop until we hit the timeout or the webpage no longer has focus
Do While dt > DateTime.Now
'Loop through all the IE windows
For Each ie In shShell.Windows
'check to see if the URL's match
If InStr(ie.LocationURL, sUrl) Then
Dim hDoc As HTMLDocument
'get the webpage document
Set hDoc = ie.document
'check to see if it has focus
If Not hDoc.hasFocus Then
ThisWorkbook.Activate
'''''''''''''
' DO EVENTS '
'''''''''''''
Exit Sub
End If
Set hDoc = Nothing
End If
Next ie
Loop
End Sub
Here's what I've ended up doing. I borrowed quite a bit from this post: How to make a macro which executes periodically in Excel?
When the user clicks on a hyperlink, the code starts periodically checking whether Excel is their active window. I've found that the GetActiveWindow function returns zero if the user is not in the Excel application and some positive number if they are. If the code finds that the user returned to Excel from a different window (the previous check found that they were in a different window and the current one finds they are in Excel) then my table gets updated and the timer stops checking for the active window.
Doing it this way has the advantage of working for any web browser.
Option Explicit
Dim ExcelIsActive As Boolean
Private Declare Function GetActiveWindow Lib "user32" () As Long
Dim m_dtNextTime As Date
Dim m_dtInterval As Date
Dim DisableFlag As Boolean
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Call start
End Sub
Public Sub Enable(Interval As Date)
Call Disable
m_dtInterval = Interval
Call starttimer
End Sub
Private Sub starttimer()
m_dtNextTime = Now + m_dtInterval
Application.OnTime m_dtNextTime, "TestActive"
End Sub
Public Sub TestActive()
If GetActiveWindow > 0 Then
If ExcelIsActive = False Then
ExcelIsActive = True
Call RefreshQuery
End If
Else
ExcelIsActive = False
End If
If Not DisableFlag Then
Call starttimer
Else
Call Disable
End If
End Sub
Public Sub Disable()
Dim dtZero As Date
If m_dtNextTime <> dtZero Then
' Stop timer if it is running
On Error Resume Next
Application.OnTime m_dtNextTime, "TestActive", , False
On Error GoTo 0
m_dtNextTime = dtZero
End If
m_dtInterval = dtZero
End Sub
Sub start()
'Start the timer
DisableFlag = False
ExcelIsActive = True
'Sets the interval to be three seconds
Call Enable(#12:00:03 AM#)
End Sub
Public Sub RefreshQuery()
'I do my stuff here
'Stop the timer until the next time the user launches the browser
DisableFlag = True
End Sub

VBA IE automation, To trigger some action in VBA before whenever i navigate to other page in website

I need a VBA code which can do some action in VBA when the webpage frame is just about to navigate to other page.for example when i click on some link,button it navigates to other page i want to take screen shot of the page before frame navigates to other.i have done something like this but it is taking screen shot of the blank page and its only working for onetime as the page is navigated and object gets changed. please help me with this i have been searching for this since 2 weeks help me.
Sub pageLoad()
Set ie2 = GetIE("https://xyz.com")
Dim LinkFound As Boolean
Dim linkCollection
Dim IEfr0 As Object
i = 0
Dim Link As MSHTML.HTMLAnchorElement
'HTMLInputElement
Set wordapp = CreateObject("word.Application")
wordapp.Visible = True
Set wrdDoc = wordapp.Documents.Add
Set IEfr0 = ie2.document.frames(0).document
Set linkCollection = IEfr0.getElementsByTagName("a")
Do While ie2.Visible = True
For Each Link In linkCollection
If ie2.document.frames(2).document.readyState = "interactive" Then
sai1
End If
If IEfr0.readyState = 1 Then
sai1
End If
Next
Loop
End Sub
Sub sai1()
Application.SendKeys "{PRTSC}"
wordapp.Selection.Paste
Do While ie2.Busy
Loop
End Sub
Here's a possible solution. Only showing you how to create the object and specify the BeforeNavigate2 event. This requires you to reference Microsoft Internet Controls and create the IE object (this will not work with late binding). This code must be in an object module (worksheet or workbook) because you cannot use WithEvents in a standard module.
Option Explicit
Dim WithEvents ie As InternetExplorer
Sub Example()
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "Your URL Here..."
Do Until ie.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
End Sub
Private Sub ie_BeforeNavigate2(ByVal pDisp As Object, URL As Variant, Flags As Variant, TargetFrameName As Variant, PostData As Variant, Headers As Variant, Cancel As Boolean)
'Place code to run before navigating here.
End Sub
An issue you may see with this is that for some websites, the BeforeNavigate2 event will actually fire multiple times due to additional calls for resources when loading.