HOWTO: Insert Event Handler Into Web Page from WebBrowser App

ID: Q185128


The information in this article applies to:
  • Microsoft Internet Explorer (Programming) versions 5.0, 4.0, 4.01


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.


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:
    Q185140 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



REFERENCES

For more information, see the MSDN Online Web Workshop:

http://msdn.microsoft.com/workshop/

(c) Microsoft Corporation 1998, All Rights Reserved. Contributions by Scott Roberts, Microsoft Corporation

Additional query words: kbDSupport kbdsi

Keywords : kbIE400 kbIE401 kbIE500 AXSDKWebBrowser
Version : WINDOWS:4.0,4.01,5.0
Platform : WINDOWS
Issue type : kbhowto


Last Reviewed: April 29, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.