IE Automation With TWAPI

Example:

package require twapi

set bIEFound 0

#-- Is IE already running?
set app [ twapi::comobj Shell.Application ]
set wnds [ $app Windows ]

set index 0
set length [ $wnds Count ]
while { $index < $length } {
  
  set itm [ $wnds Item $index ]
  
  set name [ $itm FullName ]
  set name [ string tolower $name ]
  if { [ string first "iexplore.exe" $name ] >= 0 } {
    set bIEFound 1
    set ie $itm
    set szUrl [ $ie LocationURL ]
    set szUrl [ string tolower $szUrl]

    #-- This is sometimes troublesome
    while { [ $ie Busy ] } {
      puts -nonewline "."
      flush stdout
      after 250
    }

    $ie Navigate "https://wiki.tcl-lang.org/_/search"
  
    break
  }
  
  incr index
}

if { $bIEFound } {
  
  #-- Yes; make it visible
  set w [ $ie HWND ]
  set wIE [ list $w HWND ]
  
  $ie Visible 1
  #-- Force to foreground focus
  twapi::show_window $wIE -normal -activate
  twapi::set_foreground_window $wIE

} else {
  
  #-- No; start it
  set ie [ twapi::comobj InternetExplorer.Application ]
  
  $ie Visible 0
  set szUrl "https://wiki.tcl-lang.org/_/search"
  $ie Navigate $szUrl
  $ie Visible 1

  set w [ $ie HWND ]
  set wIE [ list $w HWND ]
  
}

while { [ $ie Busy ] } {
  puts -nonewline "."
  flush stdout
  after 250
}

set doc [ $ie Document ]

while { [ $doc readyState ] != "complete" } {
 after 250
}

set body [ $doc body ]

set inputs [ $body getElementsByTagName "input" ]

set index 0
set length [ $inputs length ]
while { $index < $length } {

  set input [ $inputs item $index ]
  set name [ $input name ]
  
  if { [ string compare $name "S" ] == 0 } {
    $input value "twapi"
    $input focus

    break
  }
  
  incr index    
}

set buttons [ $body getElementsByTagName "input" ]

set index 0
set length [ $buttons length ]
while { $index < $length } {

  set button [ $buttons item $index ]
  set name [ $button name ]

  if { [ string compare $name "submit" ] == 0 } {
    $button focus
    after 250
    $button click
    break
  }
  
  incr index    
}

Scenarios:

  1. Run the script above with no IE instance running - success.
  2. Start IE and leave on default home page, then run the script above - success.
  3. Run the script above with no IE instance running, then run it again - no success. It stays in the while loop under the comment #-- This is sometimes troublesome. Apparently an IE resource is in use. The same problem occurs if this is coded using TCOM. Is anyone aware of a way to code around this problem?

see also: IE Automation With TCOM