Contents - Index - Top


VB6 - New Window Handling example

 

File(s): frmNewBrowserWindow.frm, NewWindowPopup.frm, html\loginDemoNewWindow.html, html\loginDemoNewWindowThankYou.html

 

This demo show cases how you can handle the case where the user opens a link in a new window, either from the context menu, or because the website instructs the link to be opened in a new window when clicked.

If left unhandled, then a new AntView control will be created, but you can't interact with it from your program.

 

We're displaying 3 different methods on how-to handle the new window events.

The first way is by opening the new browser in a popup in which you embedded an antview control.

The next option is to handle a new window is by ignoring the request and to redirect the URL to your current window. This has the disadvantage that it overrides the back button history, so that's gone, but no other windows to handle.

Finally there's also a way by opening the new browser window in an additional tab in a tab strip in your program.

 

Let's get started and look at some code and initialiize all the things we are going to use.

 

On loading the form we're moving around some of the frames so they show up nicely when the correct tab is selected in the tab strip, then setup the control so that we can use the hexadecimal variants of some of the events via EventsUseHexadecimal and create the webview.

 

Public WithEvents Document As AntViewAx2.AntViewDocument

Public WithEvents NewWindow As AntViewAx2.AntViewNewWindowRequestedEventArgs

Public WithEvents Deferral As AntViewAx2.AntViewDeferral

 

' The TabStrip logic comes from vb-helper.com, thanks!

' Note that the TabStrip numbers tabs starting with 1 not 0.

' The index of the selected frame.

Private SelectedTab As Integer

 

Private Sub Form_Initialize()

  Debug.Print "Form initialize"

 

  Set Document = CreateObject("AntViewAx2.AntViewDocument", "")

  Document.BrowserDispatch EdgeWebBrowser.IDispatchPointer

  Set NewWindow = CreateObject("AntViewAx2.AntViewNewWindowRequestedEventArgs", "")

  Set Deferral = CreateObject("AntViewAx2.AntViewDeferral", "")

 

  EdgeWebBrowser.UnlockControl "ExampleCompany", "WI5PO2-2KSU3Q-HWFXFU-IUMU2V-QF8P2F"

End Sub

 

Private Sub Form_Load()

  Dim i As Integer

 

  ChoiceFrame(0).Caption = ""

  ChoiceFrame(0).BorderStyle = 0

  ' Move all the frames to the same position

  ' and make them all invisible.

  For i = 1 To ChoiceFrame.UBound

      ChoiceFrame(i).Move _

          ChoiceFrame(0).Left, _

          ChoiceFrame(0).Top, _

          ChoiceFrame(0).Width, _

          ChoiceFrame(0).Height

      ChoiceFrame(i).Visible = False

      ChoiceFrame(i).Caption = ""

      ChoiceFrame(i).BorderStyle = 0

  Next i

    

  ' Select the first tab.

  SelectedTab = 1

  TabStrip1.SelectedItem = TabStrip1.Tabs(SelectedTab)

  ChoiceFrame(SelectedTab - 1).Visible = True

  EdgeWebBrowser.EventsUseHexadecimal = True ' For VB we need to use the Hexadecimal event variants

  EdgeWebBrowser.CreateWebView

  Form_Resize

End Sub

 

We're also creating 3 objects in Form_Initialize. The Document object so that we can use the documents interface, the NewWindow object, so that we can connect things and the Deferral object for being able to connect to a browser even when having to wait until it is finally created. We immediately connect the document object to the EdgeWebBrowser object instance of AntView. The TabStrip logic, slightly adjusted to our needs, is explained here:  Use the TabStrip control 

 

 

Private Sub MapLocalFolderToHostName(ByVal browser As Object)

  Dim Path As String

  Dim HostName As String

  

  Path = strGetVisualBasicDemoPath & "\html"

  HostName = "demo.internal"

  browser.SetVirtualHostNameToFolderMapping HostName, Path, hrakAllow

End Sub

 

Private Sub EdgeWebBrowser_OnCreateWebviewCompleted(ByVal HResult As Long)

  Dim IsCreated

  IsCreated = EdgeWebBrowser.WebViewCreated

  If IsCreated Then

    MapLocalFolderToHostName (EdgeWebBrowser.IDispatchPointer)

    EdgeWebBrowser.Navigate "https://demo.internal/loginDemoNewWindow.html"

  End If

End Sub

 

Once the control has been created, we first test if that went OK via WebViewCreated and if so then we setup our AntView control to treat the html folder under our application demo path as "https://demo.internal".

With that all setup, we navigate our browser control to the loginDemoNewWindow.html page.

For convenience we prefill the login form with a username and password.

 

Private Sub EdgeWebBrowser_OnNavigationCompletedHex(ByVal IsSuccess As Boolean, ByVal WebErrorStatus As AntViewAx2.TxWebErrorStatus, ByVal NavigationIdHex As String)

  If IsSuccess Then

    Document.ElementValueByName("username") = "Mr. Smith"

    Document.ElementValueByName("password") = "supersecret"

  End If

End Sub

 

As this is done in OnNavigateCompletedHex, this happens immediately after loading the loginDemoNewWindow.html page.

 

This is a simple login page that opens the new page as as we click on the "login" button within the page or the "submit" button at the bottom right.

 

<html>

<head>

  <link rel="StyleSheet" href="loginDemoNewWindow.css" type="text/css"> 

</head>

<body>

<section class="container">

    <form id="login" class="login" action="loginDemoNewWindowThankYou.html" target="_blank" method="POST">

        <div class="loginName">

            <label for="username">UserName</label>

            <input type="text" name="username" placeholder="User Name" required />

        </div>

 

        <div class="loginPassword">

            <label for="password">Password</label>

            <input type="password" name="password" placeholder="Password" required />

        </div>

 

        <div class="loginBtn">

            <button id="submit" type="submit" name="submit">Login</button>

        </div>

    </form>

</section>

    

</body>

</html>

 

The form html element has the attribute target="_blank" set and as such the submit will open in a new window.

Pfew.. OK, so far so good.

 

The request for opening a new window comes in via the OnNewWindowRequested event.

Let's go through the options, one by one.

 

 

Private Sub EdgeWebBrowser_OnNewWindowRequested(ByVal Args As AntViewAx2.IAntViewNewWindowRequestedEventArgs)

  '

  Dim URL As String

  

  If OptionRadio(0).Value = True Then

    Args.Handled = True

    URL = Args.URI

    Set NewWindow = Args

    Set Deferral = Args.Deferral

    Timer.Enabled = True ' We're using a timer for the popup so that there is no blockage if the popup is modal (which it is not in this example now)

  End If

 

The event has one parameter Args and it is of type AntViewNewWindowRequestedEventArgs.

If OptionRadio(0).Value = True.. we're going to open the link in a new window.

We tell the event that we're going to handle this New Window ourself. 

The Args.URI variable is put in a variable URL just so we can inspect it in the debugger (you can ignore that line).

The Args parameter is assigned to the NewWindow object that we had created so that its data is available from another form.

We also assign the Deferral object as Args.Deferral so that we can defer the event destroying the Args data while the application is busy trying to create a new AntView object.

The last step here is starting the timer object we have in our form by setting its Enabled property to True.

This is a one shot trigger timer that we use to start the popup from. The reason that we use a timer is that we can't start another UI object from the event and we can't pause the event itself (it must finish for AntView/WebView2 to continue working correctly).

 

Let's have a look at the timer...

 

Private Sub PopupWindow()

    Dim frmL As frmNewWindowPopup

    Set frmL = New frmNewWindowPopup

    Set frmL.Invoking = Me

    frmL.Show

End Sub

 

 

Public Sub OnTimer()

  Timer.Enabled = False

  PopupWindow

End Sub

 

Private Sub Timer_Timer()

  OnTimer

End Sub

 

The timer triggers the Timer_Timer event which calls The OnTimer sub. The first thing we do in our onTimer sub is to turn off the timer again (hence a one shot timer). Then we follow that up by executing the code we had wanted to call directly from our event, but couldn't. In this case that's PopupWindow.

PopupWindow creates the form we're about to popup and it passes the invoking form object to the public variable "Invoking".

Let's go to the NewWindowPopup form code, this form only has an AntView object and a close button so let's look at all code at once.

 

Option Explicit

Public Invoking As frmNewBrowserWindowDemo

 

Private Sub CloseButton_Click()

  '

  Unload Me

  Set frmNewWindowPopup = Nothing

End Sub

 

'

Private Sub MapLocalFolderToHostName(ByVal browser As Object)

  Dim Path As String

  Dim HostName As String

  

  Path = strGetVisualBasicDemoPath & "\html"

  HostName = "demo.internal"

  browser.SetVirtualHostNameToFolderMapping HostName, Path, hrakAllow

End Sub

 

Private Sub EdgeWebBrowser_OnCreateWebviewCompleted(ByVal HResult As Long)

  Dim IsCreated As Boolean

  IsCreated = EdgeWebBrowser.WebViewCreated

  If IsCreated Then

    MapLocalFolderToHostName (EdgeWebBrowser.IDispatchPointer)

    

    Invoking.NewWindow.NewWindowDispatch (EdgeWebBrowser.IDispatchPointer)

    Invoking.Deferral.Complete

  End If

End Sub

 

Private Sub Form_Load()

  On Error Resume Next

  Me.Show

  EdgeWebBrowser.CreateWebView

End Sub

 

OK, on loading the popup form, we create the new AntView object (EdgeWebBrowser) which eventually triggers the OnCreateWebViewCompleted event. There we first setup the folder to internal domain name mapping again, so that the url is understood. The magic is in the following two lines:

 

    Invoking.NewWindow.NewWindowDispatch (EdgeWebBrowser.IDispatchPointer)

    Invoking.Deferral.Complete

 

We can access our original form via the Invoking public variable. The objects NewWindow and Deferral in our form there are also accessible. As such we can assign the AntView object (EdgeWebBrowser) in our popup via the IDispatchPointer to the NewWindowDispatch. As our AntView object in the popup is now connected with the NewWindow event, we can let it know that we're done and send the Complete method from the deferral object.

That was the first option.

 

For the second option, we're going to open the URL in the same window.

So instead of complying with the request to open the URL in a popup window, we constrain the popup to stay within the current browser window.

This can be done in 2 ways.

 

Private Sub EdgeWebBrowser_OnNewWindowRequested(ByVal Args As AntViewAx2.IAntViewNewWindowRequestedEventArgs)

  ' ..

  ' earlier code (see above)

  ' ..

  If OptionRadio(1).Value = True Then

    Args.Handled = True

    Args.NewWindowDispatch (EdgeWebBrowser.IDispatchPointer)

  End If

 

So here we first tell the AntView that we're going to handle this ourself.

Followed by assigning the current browser's dispatch pointer to the new window dispatch pointer.

 

The other way to handle this is as follows:

 

Private Sub EdgeWebBrowser_OnNewWindowRequested(ByVal Args As AntViewAx2.IAntViewNewWindowRequestedEventArgs)

  ' ..

  If OptionRadio(1).Value = True Then

    Args.Handled = True

    EdgeWebBrowser.Navigate Args.URI

  End If

 

This time instead of letting the OnNewWindowRequested handle this further we grab the URL from Args.URI and use that to navigate.

 

The last option that we discuss here is opening the URL in a new tab page.

One might expect that the WebView2 control has tab pages, but that's not the case. The WebView2 control has no native support for tab pages. As such the AntView control has no built in tab page support either.

In order to create tabbed browser support, you have to provide the tab's from your programming language and embed a AntView control on each tab.

So in this case we use the VB6 tabstrip.

 

Private Sub EdgeWebBrowser_OnNewWindowRequested(ByVal Args As AntViewAx2.IAntViewNewWindowRequestedEventArgs)

  ' ..

  ' earlier code (see above)

  ' ..

 

  If OptionRadio(2).Value = True Then

    Args.Handled = True

    TabStrip1.Tabs.Item(2).Selected = True

    If NewTabWebBrowser.WebViewCreated = False Then

      NewTabWebBrowser.CreateWebView

      Set Deferral = Args.Deferral

      Set NewWindow = Args

    Else

      Args.NewWindowDispatch (NewTabWebBrowser.IDispatchPointer)

    End If

  End If

End Sub

 

Here we -again- tell the OnNewWindowRequested event that we're handling the event ourselves.

After that we switch to the new tab page by setting its Selected property to True.

Next up is a test to see if the webview object of the AntView control (NewTabWebBrowser) in the new tab was already created, or if it still has to be created.

If it has to be created, we call CreateWebView and use the same technique as with the popup dialog to delay the navigation with setting the deferral property and assigning the Args object to "NewWindow".

If the AntView object was already created then we can suffice by assigning the dispatch pointer of the NewTabWebBrowser to the NewWindowDispatch property.

 


AntView - The MS Edge WebView2 ActiveX control Date last changed: 09/30/2024