Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How To Insert Event Handler Into Web Page from WebBrowser App


Summary

When you are hosting the WebBrowser control in your applications, you may want to insert an event handler for a script event. This article describes how do that in a Visual Basic application.

↑ Back to the top


More information

There are three important points to note when trying to insert script for event handlers on your Web pages from your Visual Basic application.
  1. Use the insertAdjacentHTML method that is new in Internet Explorer 4.0x.
  2. You can use only JavaScript because VBScript events are bound when the page is first parsed.
  3. You must insert HTML that causes the page to be reparsed. This HTML can also be hidden. This tag "span style='display:none'" causes the HTML to be hidden and reparsed. For additional information, please see the following article in the Microsoft Knowledge Base:
    185140 PRB: Trouble Inserting Non-Displayable HTML into Web Page
  4. You must use the <SCRIPT DEFER> tag. DEFER Indicates the script block contains only functions and no in-line script. Deferring the parsing of scripts until they are needed can improve performance by decreasing the time it takes to load a document.
Use the following steps to insert script for event handlers from a Visual Basic application:
  1. Open a new Standard EXE project.
  2. Add the WebBrowser control to your form.
  3. Add a Command Button and the following code:
    Option Explicit
    
    Private Sub Command1_Click()
      Dim str As String
    
      ' Insert some hidden HTML and the script
      str = "<span style='display:none'>h</span><script defer>" & _
            "function document.onclick() {alert(1);}</script>"
    
      WebBrowser1.Document.body.insertAdjacentHTML "BeforeEnd", str
    End Sub
    
    Private Sub Form_Load()
      WebBrowser1.Navigate "http://SomeServer/SomeWebPage.htm"
    End Sub
    					
  4. You can see if the script was inserted by using the outerHTML method like this:
    Debug.Print WebBrowser1.Document.body.outerHTML

↑ Back to the top


References

For more information, see the following MSDN web site:
(c) Microsoft Corporation 1998, All Rights Reserved. Contributions by Scott Roberts, Microsoft Corporation

↑ Back to the top


Properties

Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.

↑ Back to the top


Keywords: KB185128, kbhowto

↑ Back to the top

Article Info
Article ID : 185128
Revision : 4
Created on : 7/20/2012
Published on : 7/20/2012
Exists online : False
Views : 188