Concept: QTP can control an IE window using test object, butalso use IE COM interface. In this chapter we will work on how to work with theIE COM APIs, automation of web pages using HTML DOM and change configuration ofIE through the system registry.
26.1 Launching IE
'Method 1: USE QTP SystemUtil.Run "iexplore.exe" |
'Method 2 : Use Shell Set oShell = CreateObject("WScript.Shell") oShell.Run "iexplore.exe" |
'Method 3: USE IE COM Set oIEApp = CreateObject("InternetExplorer.Application") oIEApp.Visible = True oIEApp.Navigate2 "www.baidu.com" |
When we use the third method to launch IE,we use the IE window's handle to reference the browser as a QTP test object using thefollowing code
iehwnd=oIEApp.hwnd Browser("hwnd:="&iehwnd).close |
IE COM Method
The IE Application COM interface provide many useful method and properties,we just list a few of the more common ones in the tables below:
IE COM method
Method Name | Description |
Navigate2 | navigate a specified URL |
Stop | aborts the navigation |
Refresh | Refreshes the present URL |
Quit | Close the browser |
GoBack | Navigates one page back |
GoHome | Navigate to home page |
GoForward | Navigate one page forward |
GoSearch | Open the search page |
IE COM Propertied
Properties Name | type | Description |
Left | Long | Left position of the window |
Top | Long | Top position of the window |
Width | Long | Width of the window |
Height | Long | Height of window |
AddressBar | Boolean | Controls whether address bar is shown |
FullScreen | Boolean | Maximize window and turn off statusbar,toolbar,menubar,and titlebar |
LocationName | String | Get a short(UI-friendly) name of the URL/File currently viewed |
LocationURL | string | Get the full URL/path currently viewed |
Path | string | Return the path to the application |
Resizeable | Control whether the window is resizable | |
silent | Boolean | Contol whether any dialog boxes can be shown |
Type | string | Retrun the type of contained document object |
Visible | Boolean | Determine whether the application is visible or hidden |
Busy | Boolean | Query to see if something is still in progress |
ReadyState | Long | Have any one of the following value: READYSTATE_UNINITIALIZED; READYSTATE_LOADING; READYSTATE_LOADED; READYSTATE_INTERACTIVE; READYSTATE_COMPLETE. |
Page synchronization
We can use busy property to determine whether IE is busy loading,the following example
Explains how we can wait for a page to load(note:this method can not work properly when the page has frame)
Set oIEApp = CreateObject("InternetExplorer.Application") oIEApp.Visible = True oIEApp.Navigate2 "www.baidu.com" Do a=2 Loop while oIEApp.busy=true msgbox "Page Loaded"
|
Enumerating all IE windows
'Function to enumerate all open IE windows 'This is needed in case an IE window is closed 'while this function is executing On Error Resume Next
'Create a dictionary for returning the collection of open IE windows Set EnumerateIE = CreateObject("Scripting.Dictionary")
'Get the windows shell application Set oWinShell = CreateObject("Shell.Application")
'Get a collection all open explore windows, 'Microsoft Explorer + Internet Explorer Set allWindows = oWinShell.Windows
'Loop through each window For Each oWindow In allWindows 'Check if it is internet explorer process then only add it If InStr(1, oWindow.FullName, "iexplore.exe",vbTextCompare) Then
EnumerateIE.Add oWindow.hwnd, oWindow End if Next End Function
'usage set all=EnumerateIE() For each oIE in all.items oIE.quit Next |
The code above can work in a pure vbscript without QTP,but in QTP we can also close IE with a single line of statement :
systemUtil.CloseProcessByName(“iexplore.exe”) |
Finding an IE window
use the enumeration method above to search for an IE window,and we can search the IE window using its window's handle
Function GetIECOMByHwnd(byval ieHwnd) Set GetIECOMByHwnd=nothing set all=EnumerateIE() For each oIE in all.items If oIE.hwnd=ieHwnd Then '发现相关的IE窗口,返回他的COM接口对象 set GetIECOMByHwnd=oIE End If
Next End Function |
similarly we can search the IE window using its URL(if multiple browers have been opened with the same URL,it may return any one of the browser)
Function GetIECOMByURL(ByVal ieURL) 'Return Nothing in case no windows are found Set GetIECOMByURL = Nothing
Set allIE = EnumerateIE()
For Each oIE In allIE.Items If InStr(oIE.LocationURL, ieURL) Then 'We found the associated IE window. Return its COM interface object Set GetIECOMByURL = oIE
Exit Function End If Next End Function |
Launching a new browser
If multiple IE windows were opened,how can we determine which one is launched by QTP,we can open the browser with a random number and then search the IE window(COM interface) using GetIECOMByURL function just created
'Generate a random string of digits of specified length Function GetRandomNumberByLen(ByVal Length) GetRandomNumberByLen = ""
'Generate the random number digit by digit For i = 1 To Length 'Seed the radom generator with current timer Randomize Timer()
'Generate and append the random number iRnd = CInt((9)*Rnd()) iRnd = CStr(iRnd) GetRandomNumberByLen = GetRandomNumberByLen & iRnd Next End Function
'Function to get a new browser Function GetNewBrowser() Set GetNewBrowser = Nothing
'This is to store the random browser id generated 'which can be later used to recognize the browser 'which was launched browserID = GetRandomNumberByLen(10)
SystemUtil.Run "iexplore.exe", "about:" & browserID
'Wait for few seconds to make sure the process launches Wait 3 Set GetNewBrowser = GetIECOMByURL(browserID) End Function
'Get a new browser Set oBrowser = GetNewBrowser()
'Naviagte to a URL in the opened browser oBrowser.Navigate2 "http://www.baidu.com" |
Getting the Web page DOM
IE COM interface expose the document object,the following technique can be run in pure VBScript without QTP
'Create an IE application Set oIE = CreateObject("InternetExplorer.Application")
'Make the application visible oIE.Visible = True
'Navigate to a web site oIE.Navigate2 "www.baidu.com" While oIE.Busy: Wend
'Get DOM document object Set oDOMDoc = oIE.Document
'Get all INPUT tag elements Set allInput = oDOMDoc.getElementsByTagName("INPUT")
'Loop through all INPUT elements and 'set the value for all text boxes on the page For Each oInput In allInput If oInput.type = "text" Then oInput.Value = "Set by IE COM/DOM access" End If Next |
The detail about DOM,refer to the Chapter:html DOM
Accessing webpage script variable
Consider the below html source code
<html> <SCRIPT language="JavaScript">var PageName2 = {}; PageName2["val1"] = "Tarun1"; PageName2["val2"] = "Tarun2"; </SCRIPT> <body> <SCRIPT language="VBScript"> Const PageName = "Tarun Lalwani" Dim arr(1) Arr(0) = "Array 1" Arr(1) = "Array 2" Public Sub Func1(a, b) Msgbox a + b End Sub </SCRIPT> </body> </html> |
'Get the Page test object Set oPG = Browser("creationtime:=0").Page("micclass:=Page")
'Displays "Tarun Lalwani " Msgbox oPG.object.parentWindow.PageName
'Displays "Array 1" Msgbox oPG.object.parentWindow.arr(0)
'Displays "Tarun1" Msgbox oPG.object.parentWindow.PageName2.Val1
'Displays a message box with value 5 in the browser Call oPG.object.parentWindow.Func1(2,3) |
Using IE to get user input
'C:\Files.html <SCRIPT language="vbscript"> Dim userAction </SCRIPT>
<P>UserName: <INPUT type=text name=username value="Enter user name">
<P>Password: <INPUT type=password name=password>
<P>Environment: <SELECT type=select name=env> <OPTION>Test1</OPTION> <OPTION>Test2</OPTION> </SELECT> <P>
<INPUT type=button value="Submit" οnclick="vbscript:userAction='Submitted'">
<INPUT type=button value="Cancel" οnclick="vbscript:userAction='Cancelled'"> |
'Start a new browser SystemUtil.Run "iexplore.exe", "C:\files.html"
Set oBrw = Browser("micclass:=Browser") Set oPg = oBrw.Page("micclass:=Page")
oBrw.Sync
'Resize the browser oBrw.Object.Left = 350 oBrw.Object.Top = 300 oBrw.Object.Height = 200 oBrw.Object.Width = 300
'Disable all other browser features oBrw.Object.AddressBar = False oBrw.Object.Resizable = False oBrw.Object.StatusBar = False oBrw.Object.ToolBar = False
'Activate the browser window Window("hwnd:=" & oBrw.GetROProperty("hwnd")).Activate
'Set the user action to blank oBrw.object.Document.parentWindow.userAction = ""
'When user click submit or cancel button this userAction 'variable will be populated with a value While oBrw.object.Document.parentWindow.userAction = "" Wait 1 wend
If oBrw.object.Document.parentWindow.userAction = "Cancelled" Then 'Check if user clicked cancelled Msgbox "User clicked cancelled" Else 'User clicked Submit. Get the values Msgbox oPg.WebEdit("name:=username").GetROProperty("value") Msgbox oPg.WebEdit("name:=password").GetROProperty("value") Msgbox oPg.WebList("name:=env").GetROProperty("value") End If |
IE Popup Dialogs
有时候因为环境不同,有的应用程序在一台机子上可能弹出安全提示等,在另一台机子上却不会。有两种方法可以阻止这些弹出框,一种是针对各种弹出框写相应的代码,采取必要的措施忽略他们,另一种方法是修改IE的设置
We can use the silent property to disable the display of IE dialog box
Browser(“..”).Object.Silent = True |
But this solution is seldom the appropriate one because the default button of the dialog is no,then it will take a acton as ‘no was clicked’,so the following solution will be a good choice
Changing IE Settings
Window’s Shell object provide the regWrite,regDelete,regRead to access and modify the window’s registry
思路:这中办法在项目中经常应用,可以改变windows注册信息。 不过要小心点使用,而且建议改完后再恢复原值。
'Create a Window's shell object Set WshShell = CreateObject("WScript.Shell")
'Write to the registry WshShell.RegWrite "HKCU\Software\Microsoft\TestThis", "TESTValue", "REG_SZ"
'Read from the Registry Msgbox WshShell.RegRead("HKCU\Software\Microsoft\TestThis")
'Delete a registry key Msgbox WshShell.RegDelete("HKCU\Software\Microsoft\TestThis") |
Popup Blocker
Dialog infor: Pop-up blocked. To see this popup or additionalaptions click here…….
1st method:
Set WshShell = CreateObject("WScript.Shell")
popupKeyPath = "HKCU\Software\Microsoft\Internet Explorer\New Windows\PopupMgr"
'Disable IE popup blocked
WshShell.RegWrite popupKeyPath,"no", "REG_SZ"
'Able IE popup blocked
WshShell.RegWrite popupKeyPath, "yes", "REG_SZ" |
2nd method: Add this website to the “popup allowed” list by following code:
sDomain= "http://www.crsky.com/soft/5271.html"
popupAllowKey = "HKCU\Software\Microsoft\Internet Explorer\New Windows\Allow\"
WshShell.RegWrite popupAllowKey & sDomain, 0 , "REG_BINARY" |
Disable Sript Error dialog
Note: QTP error dialogs, e.g. runtime error dialogs:
‘Disable all script debug dialogs WshShell.RegWrite “HKCU\Software\Microsoft\Internet Explorer\Main\Disable Script Debugger”, “yes”, “REG_SZ” WshShell.RegWrite “HKCU\Software\Microsoft\Internet Explorer\Main\Disable Script DebuggerIE”, “yes”, “REG_SZ” WshShell.RegWrite “HKCU\Software\Microsoft\Internet Explorer\Main\Error Dlg Displayed On Every Error”, “no”, “REG_SZ” |
Security Alert –Redirection popup
Note: Infor: You are redirected to a connection that is not secure …….
‘Disable the dialogs WshShell.RegWrite “HKCU\Software\Microsoft\Windows\CurrentVersion\Internet_ Setting\WarnOnPosRedirect”, “no”, “REG_SZ” |
Security Alert –Certificate warning
Note: Infor: Informationyou exchange with this site cannot be viewed or changed by others. However …….
‘Disable the dialogs WshShell.RegWrite “HKCU\Software\Microsoft\Windows\CurrentVersion\Internet_ Setting\”, “no”, “REG_SZ” |
Security Alert –Secure Connection
Note: Infor: You are about to view pages over a secure connection……..
‘Disable the dialogs WshShell.RegWrite “HKCU HKCU\Software\Microsoft\Windows\CurrentVersion\Internet_Setting\WarnOnPost”, “no”, “REG_SZ” |
Security Information –Secure and non-secure item
Note1: Infor: This page contains both secure and nonsecure items…….
Note2: Security information settings are stored in a zone. Thereare five different zones in IE setting:
-- My Computer -- Local Intranet Zone -- Trusted sites Zone -- Internet Zone -- Restricted Sites Zone |
Each setting belonging to a above zone has its correspondingcode. Pls find codes in MS KB article 182569 (http://support.microsoft.com/kb/182569)
'Various zone codes 'Value Setting '------------------------------ '0 My Computer '1 Local Intranet Zone '2 Trusted sites Zone '3 Internet Zone '4 Restricted Sites Zone
'0 - enabled, 1 - prompt, 3 - disabled newValue = 0
'Disable the Security information secure non-secure popup in all the Zones SettingCode = "1609"
'Change the setting for all 5 zones For i = 0 To 4 ChangeIEZoneSetting CStr(i), SettingCode, newValue Next
'Function to change specified setting in a specified zone Function ChangeIEZoneSetting(ByVal ZoneCode, ByVal SettingCode, ByVal newValue) Dim WshShell Set WshShell = CreateObject("WScript.Shell")
keyPath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones" WshShell.RegWrite keyPath & "\" & ZoneCode & "\" & SettingCode, newValue, "REG_DWORD" End Function |
Active content/ Java Script prompt
Note: Infor: To help protect your security, Internet Explorer has restricted this file……
'Various zone codes 'Value Setting '------------------------------ '0 My Computer '1 Local Intranet Zone '2 Trusted sites Zone '3 Internet Zone '4 Restricted Sites Zone
'0 - enabled, 1 - prompt, 3 - disabled newValue = 0
'Disable all the Zones SettingCode = "1400"
'Change the setting for all 5 zones For i = 0 To 4 ChangeIEZoneSetting CStr(i), SettingCode, newValue Next
|
File Download -- Information Bar
Note: Infor: To help protect your security, Internet Explorer has blocked this site from downloading files ……
'Various zone codes 'Value Setting '------------------------------ '0 My Computer '1 Local Intranet Zone '2 Trusted sites Zone '3 Internet Zone '4 Restricted Sites Zone
'0 - enabled, 1 - prompt, 3 - disabled newValue = 0
'Disable all the Zones SettingCode = "2200"
'Change the setting for all 5 zones For i = 0 To 4 ChangeIEZoneSetting CStr(i), SettingCode, newValue Next |
Handing popup dialog by using a code:
'Public Function CleanBrowserPopups(oBrw) 'Get the popup dialog Set oPopDlg = oBrw.Dialog("ispopupwindow:=True")
CleanBrowserPopups = False If oPopDlg .Exist(0) Then 'There is a popup dialog 'Get its title sPopTitle = oPopDlg.GetROProperty("title")
Select Case LCase(sPopTitle) Case "security information", "security alert", "security warning" "error" 'Either a OK button would be there or a yes button 'Use a regular expression to cater both in a single statement oPopDlg.WinButton("text:=(&Yes|OK)").Click CleanBrowserPopups = True Reporter.ReportEvent micPass, sPopTitle, "Closed IE dialog popup" Case "enter network password" 'CODE to handle enter network password widows 'this is application to Windows 2000 OS Case Else If Left(LCase(sPopTitle),10) = "connect to" Then 'CODE to handle enter network password windows 'this is application to Windows XP OS Else MsgBox "Unknown dialog box - " & sPopTitle End If End Select End If End Function
'We can register this as user defined user method RegisterUserFunc "Browser", "CleanBrowserPopups", "CleanBrowserPopups"
If Browser("creationtime:=0").CleanBrowserPopups = True Then MsgBox "Cleaned all dialogs in the browser" End if |
It would make it more convenient to intergrate the above function with the Browser and Page
Sync method,we can do that by using the code given below
File Dowloading –Security Warning popup
思考: 就是通过DP拿到对象。
There are 3 dialogs occur:
--File Download – SecurityWarning
--Save As
--File Download
'Function to download a file from IE Public Function IEDownloadFile(ByVal oDlg, ByVal sFileName, ByVal bWaitComplete) sPopup = "ispopupwindow:=true" sBtn = "nativeclass:=button"
'We will use window handle because the title will change later 'From "File Download" to "Download Complete", but handle will remain 'the same hWnd = oDlg.GetROProperty("hwnd")
With Dialog("hwnd:=" & hwnd) 'Get the value of the close on download complete checkbox sCloseAfterDownload=.WinCheckBox(sBtn,"text:=&Close.*").GetROProperty("checked")
'Check if the security wanring dialog is present If .Dialog(sPopup).Exist(0) Then 'Two click events needed sometimes as the first one does not do anything .Dialog(sPopup).WinButton("text:=&Save",sBtn).Click 'Make the second click option in case the first one works 'And to use OptionalStep we need to use the Complete statement OptionalStep.Dialog("hwnd:=" & hwnd).Dialog(sPopup).WinButton("text:=&Save",sBtn).Click End if
'Enter the complete file name in the save windo hwnd=.Dialog(sPopup).GetROProperty("hwnd") .Dialog(sPopup).Activate .Dialog(sPopup).WinEdit("nativeclass:=Edit","attached text:=File &name\:").Set "" .Dialog(sPopup).WinEdit("nativeclass:=Edit","attached text:=File &name\:").Type sFileName .Dialog(sPopup).WinButton(sBtn,"text:=&Save").Click
'Check if the file already exist dialog has appeared 'We get the Save As dialog handle and then check for the 'File allready exist. Going by the normal way we would have used 'Dialog("hwnd:=" & hwnd).Dialog(sPopup).Dialog(sPopup).Exist(0) 'Which is expected to work but it does not. So to reduce one level 'of hierarchy we take the hWnd and use it If Dialog("hwnd:=" & hwnd).Dialog(sPopup).Exist(0) Then Dialog("hwnd:=" & hwnd).Dialog(sPopup).WinButton(sBtn,"text:=&Yes").Click End If
If bWaitComplete Then 'Once download is complete either the window is closed if the checkbox 'was checked or the Open Folder on the window will change get enabled While .Exist(0) and Not .WinButton("text:=Open &Folder").GetROProperty("enabled") Wait 1 Wend
'If the checkbox OFF then we need to close the dialog If sCloseAfterDownload = "OFF" then .Close End if End with End Function
'------------------------------------------------------------------------------------------ 'Get the dialog window Set oDlg = Dialog("text:=File Download","Index:=0")
'Download the file synchronously IEDownloadFile oDlg , "C:\Test.exe", True Msgbox "Download Complete"
'Download the file asynchronously IEDownloadFile oDlg , "C:\Test.exe", False MsgBox "The download has started" |
Checking for Broken images on a web page
Note: Broken image has following property values:
--fileSize = -1
--readyState = “uninitialized”
思路: 利用htmlDom 得到image的属性值, 和上面的value相比。
'Function to Check for broken images on a page Public Function CheckBrokenImages(oPage) pgTitle = oPage.GetROProperty("title") Set allImages = oPage.object.Images iCount = allImages.Length - 1
For i = 0 To iCount Set curIMG = allImages.item(i) sHTML = "HTML = " & curIMG.outerHTML If curIMG.fileSize = -1 Then 'The image did not load Reporter.ReportEvent micFail, pgTitle & "Broken Image", sHTML Else Reporter.ReportEvent micPass, pgTitle & "Valid Image", sHTML End if Next End Function
'Usage CheckBrokenImages Browser("micclass:=Browser","index:=0").Page("micclass:=Page") |
Using a Browser Object as a Window Object
Note: 有时候你要用Window的自带方法,就把Browser转换为Window。
‘Use windows handle property (hwnd) hwnd = Brwser(“”).GetROProperty(“hwnd”) Set oBrowserWindow = Window(“hwnd:= &hwnd”) ‘now you can use any window method
'Window methods being used with the Browser Public Function BrowserType(oBrw, Text) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Type hwnd End Function
Public Function BrowserMaximize(oBrw) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Maximize End Function
Public Function BrowserMinimize(oBrw) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Minimize End Function
Public Function BrowserDblClick(oBrw, X, Y, MouseButton) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).DblClick X, Y, MouseButton End Function
Public Function BrowserResize(oBrw, width, heigh) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Resize width, height End Function
Public Function BrowserRestore(oBrw) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Restore End Function
Public Function BrowserMouseMove(oBrw, X, Y) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).MouseMove X, Y End Function
Public Function BrowserMove(oBrw, X, Y) Dim hwnd hwnd = oBrw.GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Move X, Y End Function
Public Function BrowserhWnd(oBrw) hwnd = oBrw.GetROProperty("hwnd") End Function
RegisterUserFunc "Browser", "Maximize", "BrowserMaximize" RegisterUserFunc "Browser", "Minimize", "BrowserMinimize" RegisterUserFunc "Browser", "DblClick", "BrowserDblClick" RegisterUserFunc "Browser", "Resize" , "BrowserResize" RegisterUserFunc "Browser", "Restore", "BrowserRestore" RegisterUserFunc "Browser", "MouseMove", "BrowserMouseMove" RegisterUserFunc "Browser", "Move" ,"BrowserMove" RegisterUserFunc "Browser", "hWnd" ,"BrowserhWnd" |