2011-09-02

Accessing IE from vbScript

It used to be simple to use Internet Explorer as output for vbScripts. Here is a sample script that opened a custom HTML page and then writes something into a <div id="Status">...</div> stanza.

Dim objIE
Set objIE = WScript.CreateObject ("InternetExplorer.Application")
objIE.Width = 700
objIE.Height = 250
objIE.Toolbar = false
objIE.statusbar = false
objIE.Navigate "D:\Test\Output.html"
objIE.Visible = true
objIE.document.all.Status.InnerHTML = "<font color='#0063FF'><b>Done... waiting 5 secs...</b></font>"
WScript.Sleep (5000)
objIE.Quit


Now with Windows 7 and IE 9 many of those scripts do no longer run but throw errors. Common errors are for example: "The object invoked has disconnected from its client." (80010108) or "Unspecified error" (80004005)

It seems that the original Internet Explorer object gets lost because the web page is loaded into a child process of IE. So any reference to it from a vbScript fails.

A few changes to the above script can work around that issue. It may not be the most elegant but it is working so far.

Dim objIE
Set objIE = WScript.CreateObject ("InternetExplorer.Application")
Set objShellApp = CreateObject("Shell.Application")
objIE.Width = 700
objIE.Height = 250
objIE.Toolbar = false
objIE.statusbar = false
objIE.Navigate "D:\Test\Output.html"
objIE.Visible = true
Set objIE = Nothing
For Each objWindow In objShellApp.Windows
If LCase(objWindow.LocationName) = LCase("Output.html") Then
Set objIE = objWindow
End If
Next
objIE.document.all.Status.InnerHTML = "<font color='#0063FF'><b>Done... waiting 5 secs...</b></font>"
WScript.Sleep (5000)
objIE.Quit

Basically we are looping through all windows and connect (hopefully ;-) ) to the one that has our HTML file open.

3 comments:

  1. This is brilliant, I was scratching my head for ages over this problem. Thank you.

    ReplyDelete
  2. This situation has been noted on Win7/IE9 for sites that are members of the Trusted Site Zone. None of the following has been experienced for URLs that are not members of the Trusted Site Zone. “Enable Protected Mode” in the Trusted Site Zone is NOT checked.

    The first issue is that objIE.Navigate causes URLs in the Trusted Site zone to immediately open in Visible mode. The objIE.Visible command is not necessary to make the page appear.

    The second issue is that there is about a 10 millisecond delay from when the objIE.Navigate command is issued for a URL in the Trusted Site zone and when the associated object is unmapped. After the 10 milliseconds have passed, one of the following errors will occur upon subsequent calls to objIE. This is why the objIE.Visible call apparently works but the objIE.Document results in an error.

    “Unspecified error” (80004005)
    "The interface is unknown." (800706B5)
    “The object invoked has disconnected from its client.” (80010108)

    ReplyDelete
    Replies
    1. Should we use this code for each instance of IE.Navigate ?

      Delete