There are three important points to note when trying to insert script for
event handlers on your Web pages from your Visual Basic application.
- Use the insertAdjacentHTML method that is new in Internet Explorer 4.0x.
- You can use only JavaScript because VBScript events are bound when the
page is first parsed.
- 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
- 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:
- Open a new Standard EXE project.
- Add the WebBrowser control to your form.
- 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
- You can see if the script was inserted by using the outerHTML method
like this:
Debug.Print WebBrowser1.Document.body.outerHTML