为什么我无法重新打开浏览器(对象)?

问题描述:

我想创建一个脚本来打开Internet Explorer浏览器,但有一些限制。该脚本验证iexplorer.exe进程是否正在运行,如果没有(表示浏览器已关闭),则在10秒后自动重新打开该进程。为什么我无法重新打开浏览器(对象)?

这是脚本:

strComputer = "." 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set objShell = CreateObject("Wscript.Shell") 
Set objExplorer = CreateObject("InternetExplorer.Application") 
Const REOPEN_AFTER =10000 


objExplorer.Navigate "http://www.google.com" 
objExplorer.Visible = true 
objExplorer.ToolBar = false 
objExplorer.MenuBar = false 
objExplorer.StatusBar = false 
objExplorer.AddressBar = true 
objExplorer.Width = 1280 
objExplorer.Height = 1024 
objExplorer.Left = 0 
objExplorer.Top = 0 
objExplorer.Resizable = false 

Do While True 
    Set colProcesses = objWMIService.ExecQuery _ 
     ("Select * from Win32_Process Where Name = 'iexplore.exe'") 
    If colProcesses.Count = False Then 
     objExplorer.Navigate "http://www.google.com" 
     objExplorer.Visible = true 

    End If 
    Wscript.Sleep REOPEN_AFTER 
Loop 

如果我开始运行时,它打开浏览器脚本,但如果我关闭它,它不会重新打开它。

但是,如果我像这样运行它,然后它的工作原理:

strComputer = "." 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set objShell = CreateObject("Wscript.Shell") 
Set objExplorer = CreateObject("InternetExplorer.Application") 
Const REOPEN_AFTER =10000 


objExplorer.Navigate "http://www.google.com" 
objExplorer.Visible = true 
objExplorer.ToolBar = false 
objExplorer.MenuBar = false 
objExplorer.StatusBar = false 
objExplorer.AddressBar = true 
objExplorer.Width = 1280 
objExplorer.Height = 1024 
objExplorer.Left = 0 
objExplorer.Top = 0 
objExplorer.Resizable = false 

Do While True 
    Set colProcesses = objWMIService.ExecQuery _ 
     ("Select * from Win32_Process Where Name = 'iexplore.exe'") 
    If colProcesses.Count = 0 Then 
     objShell.Run "iexplorer.exe" 
    End If 
    Wscript.Sleep REOPEN_AFTER 
Loop 

有人能看到的错误是什么?

我认为当你关闭浏览器,objExplorer是无效的,当你尝试

If colProcesses.Count = False Then 
    objExplorer.Navigate "http://www.google.com" 
    objExplorer.Visible = true 
End If 

,因为它并不指向一个打开的浏览器就会失败了 - 我想你只需要创建一个新的IE的实例,例如:

function createExplorer 

    Set createExplorer = CreateObject("InternetExplorer.Application") 
    createExplorer.Navigate "http://www.google.com" 
    createExplorer.Visible = true 
    createExplorer.ToolBar = false 
    createExplorer.MenuBar = false 
    createExplorer.StatusBar = false 
    createExplorer.AddressBar = true 
    createExplorer.Width = 1280 
    createExplorer.Height = 1024 
    createExplorer.Left = 0 
    createExplorer.Top = 0 
    createExplorer.Resizable = false 

end function 



Do While True 
    Set colProcesses = objWMIService.ExecQuery _ 
    ("Select * from Win32_Process Where Name = 'iexplore.exe'") 
    If colProcesses.Count = 0 Then 
     Set objExplorer = createExplorer() 
    End If 
    Wscript.Sleep REOPEN_AFTER 
Loop 

移动对象实例化的if colProcesses.Count=0 Then

内。当导航器被关闭时,存储在该变量中的对象的引用是无效的。你需要一个新的实例。