Class: Vapir::IE

Inherits:
Browser
  • Object
show all
Extended by:
Configurable, ClearTracksMethods
Includes:
Exception, ClearTracksMethods, PageContainer
Defined in:
lib/vapir-ie/config.rb,
lib/vapir-ie/browser.rb,
lib/vapir-ie/process.rb,
lib/vapir-ie/version.rb,
lib/vapir-ie/close_all.rb,
lib/vapir-ie/ie-process.rb,
lib/vapir-ie/clear_tracks.rb

Defined Under Namespace

Modules: ClearTracks, ClearTracksMethods, Container, PageContainer, RefreshConstants Classes: Area, Button, CheckBox, Dd, Div, Dl, Dt, Element, Em, FileField, H1, H2, H3, H4, H5, H6, Hidden, InputElement, Label, Li, Map, ModalDialog, ModalDialogDocument, Ol, Option, P, Pre, Process, Radio, SelectList, Span, Strong, TextField, Ul

Constant Summary collapse

EMPTY_TAG_NAME =

IE inserts some element whose tagName is empty and just acts as block level element Probably some IE method of cleaning things To pass the same to the xml parser we need to give some name to empty tagName

"DUMMY"
ExistenceFailureCodesRE =

we expect one of these error codes when quitting or checking existence.

Regexp.new(
{ '0x800706ba' => 'The RPC server is unavailable',
  '0x80010108' => 'The object invoked has disconnected from its clients.',
  '0x800706be' => 'The remote procedure call failed.',
  '0x800706b5' => 'The interface is unknown.',
  '0x80004002' => 'No such interface supported',
  '0x80004001' => 'unknown property or method',
  '0x80004005' => '<No Description>',
  '0x80020101' => '<No Description>', # this one gets raised from watir_wrap_native_for_win32ole_two_args when it stops existing 
}.keys.join('|'), Regexp::IGNORECASE)
VERSION =
'1.10.1'

Constants included from PageContainer

PageContainer::READYSTATE_COMPLETE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClearTracksMethods

clear_all_tracks, clear_cookies, clear_history, clear_temporary_files

Methods included from PageContainer

#check_for_http_error, #content_window_object, #execute_script, #html, #text, #wait

Methods included from Container

#handling_existence_failure

Constructor Details

#initialize(method_options = {}) ⇒ IE

Create an IE browser.

Takes a hash of options:

  • :timeout - the number of seconds to wait for a window to appear when attaching or launching.

  • :goto - a url to which the IE browser will navigate. by default this is ‘about:blank’ for newly-launched IE instances, and the default is not to navigate anywhere for attached instances.

  • :new_process - true or false, default is false. whether to launch this IE instance as its own process (this has no effect if :attach is specified)

  • :attach - a two-element Array of [how, what] where how is one of:

    • :title - a string or regexp matching the title of the browser that should be attached to.

    • :URL - a string or regexp matching the URL of the browser that should be attached to.

    • :HWND - specifies the HWND of the browser that should be attached to.

    • :name - the name of the window (as specified in the second argument to a window.open() javascript call)

    • :browser_object - this is generally just used internally. ‘what’ is a WIN32OLE object representing the browser.

    • :wait - true or false, default is true. whether to wait for the browser to be ready before continuing.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/vapir-ie/browser.rb', line 95

def initialize(method_options = {})
  if method_options==true || method_options==false
    raise NotImplementedError, "#{self.class.name}.new takes an options hash - passing a boolean for 'suppress_new_window' is no longer supported. Please see the documentation for #{self.class}.new"
  end
  options = options_from_config(method_options, {:timeout => :attach_timeout, :new_process => :ie_launch_new_process, :wait => :wait, :visible => :browser_visible}, [:attach, :goto])

  @error_checkers = []
  
  @logger = DefaultLogger.new
  @url_list = []

  if options[:attach]
    how, what = *options[:attach]
    if how== :browser_object
      @browser_object = what
    else
      orig_how=how
      hows={
        :title => proc{|bo| bo.document.title },
        :URL => proc{|bo| bo.locationURL },
        :name => proc{|bo| bo.document.parentWindow.name },
        :HWND => proc{|bo| Vapir::IE.fix_win32ole_hwnd(bo.HWND) },
      }
      how=hows.keys.detect{|h| h.to_s.downcase==orig_how.to_s.downcase}
      raise ArgumentError, "how should be one of: #{hows.keys.inspect} (was #{orig_how.inspect})" unless how
      @browser_object = ::Waiter.try_for(options[:timeout], :exception => NoMatchingWindowFoundException.new("Unable to locate a window with #{how} of #{what.inspect}")) do
        self.class.browser_objects.detect do |browser_object|
          begin
            Vapir::fuzzy_match(hows[how].call(browser_object), what)
          rescue WIN32OLERuntimeError, NoMethodError
            false
          end
        end
      end
    end
    if method_options.key?(:visible)
      # only set visibility if it's explicitly in the options given to the method - don't set from config when using attach 
      self.visible= method_options[:visible]
    end
  else
    if options[:new_process]
      iep = Process.start
      @browser_object = iep.browser_object(:timeout => options[:timeout])
      @process_id = iep.process_id
    else
      @browser_object = WIN32OLE.new('InternetExplorer.Application')
    end
    self.visible= options[:visible]
    goto('about:blank')
  end
  goto(options[:goto]) if options[:goto]
  wait if options[:wait]
  self
end

Instance Attribute Details

#browser_objectObject (readonly) Also known as: ie



163
164
165
# File 'lib/vapir-ie/browser.rb', line 163

def browser_object
  @browser_object
end

#down_load_timeObject (readonly)

The time, in seconds, it took for the new page to load after executing the the last command



21
22
23
# File 'lib/vapir-ie/browser.rb', line 21

def down_load_time
  @down_load_time
end

#loggerObject

access to the logger object



24
25
26
# File 'lib/vapir-ie/browser.rb', line 24

def logger
  @logger
end

#url_listObject (readonly)

this contains the list of unique urls that have been visited



27
28
29
# File 'lib/vapir-ie/browser.rb', line 27

def url_list
  @url_list
end

Class Method Details

.browser_objectsObject



66
67
68
# File 'lib/vapir-ie/browser.rb', line 66

def browser_objects
  Enumerator.new(self, :each_browser_object)
end

.browsersObject



53
54
55
# File 'lib/vapir-ie/browser.rb', line 53

def browsers
  Enumerator.new(self, :each_browser)
end

.close_allObject

close all ie browser windows



6
7
8
# File 'lib/vapir-ie/close_all.rb', line 6

def self.close_all
  close_all_but nil
end

.each_browserObject Also known as: each

Yields successively to each IE window on the current desktop. Takes a block. This method will not work when Vapir/Ruby is run under a service (instead of a user). Yields to the window and its hwnd.



47
48
49
50
51
# File 'lib/vapir-ie/browser.rb', line 47

def each_browser
  each_browser_object do |browser_object|
    yield attach(:browser_object, browser_object)
  end
end

.each_browser_objectObject

yields a WIN32OLE of each IE browser object that is available.



58
59
60
61
62
63
64
65
# File 'lib/vapir-ie/browser.rb', line 58

def each_browser_object
  shell = WIN32OLE.new('Shell.Application')
  shell.Windows.each do |window|
    if (window.path =~ /Internet Explorer/ rescue false) && (window.hwnd rescue false)
      yield window
    end
  end
end

.fix_win32ole_hwnd(win32ole_hwnd) ⇒ Object

win32ole’s #HWND method casts to signed somewhere along its way, so returns a negative number. this is wrong, WinWindow will reject it (correctly), so we need to fix.



175
176
177
# File 'lib/vapir-ie/browser.rb', line 175

def self.fix_win32ole_hwnd(win32ole_hwnd)
  win32ole_hwnd < 0 ? win32ole_hwnd % 2**32 : win32ole_hwnd
end

.new_process(options = {}) ⇒ Object

Create a new IE window in a new process. This method will not work when Vapir/Ruby is run under a service (instead of a user).



33
34
35
# File 'lib/vapir-ie/browser.rb', line 33

def new_process(options={})
  new(options.merge(:new_process => true))
end

.process_countObject

Returns the number of IEXPLORE processes currently running.



18
19
20
# File 'lib/vapir-ie/process.rb', line 18

def self.process_count
  Vapir::Process.count 'iexplore.exe'
end

.start_process(url = 'about:blank', options = {}) ⇒ Object

Create a new IE window in a new process, starting at the specified URL. Same as IE.start.



39
40
41
# File 'lib/vapir-ie/browser.rb', line 39

def start_process(url='about:blank', options={})
  new(options.merge(:new_process => true, :goto => url))
end

.versionObject

the version string, from the registry key HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerVersion



6
7
8
9
10
11
12
13
14
# File 'lib/vapir-ie/ie-process.rb', line 6

def self.version
  @@ie_version ||= begin
    require 'win32/registry'
    ::Win32::Registry::HKEY_LOCAL_MACHINE.open("SOFTWARE\\Microsoft\\Internet Explorer") do |ie_key|
      ie_key.read('Version').last
    end
    # OR: ::WIN32OLE.new("WScript.Shell").RegRead("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Version")
  end
end

.version_partsObject

the version string divided into its numeric parts returned as an array of integers



16
17
18
# File 'lib/vapir-ie/ie-process.rb', line 16

def self.version_parts
  @@ie_version_parts ||= IE.version.split('.').map{|part| part.to_i }
end

Instance Method Details

#add_checker(checker) ⇒ Object

this method is used to add an error checker that gets executed on every page load

  • checker Proc Object, that contains the code to be run



423
424
425
# File 'lib/vapir-ie/browser.rb', line 423

def add_checker(checker)
  @error_checkers << checker
end

#backObject

Go to the previous page - the same as clicking the browsers back button an WIN32OLERuntimeError exception is raised if the browser cant go back



275
276
277
278
279
280
# File 'lib/vapir-ie/browser.rb', line 275

def back
  assert_exists do
    @browser_object.GoBack
    wait
  end
end

#bring_to_frontObject

Make the window come to the front



348
349
350
# File 'lib/vapir-ie/browser.rb', line 348

def bring_to_front
  win_window.really_set_foreground!
end

#browserObject



402
403
404
# File 'lib/vapir-ie/browser.rb', line 402

def browser
  self
end

#clear_url_listObject

clear the list of urls that we have visited



307
308
309
# File 'lib/vapir-ie/browser.rb', line 307

def clear_url_list
  @url_list.clear
end

#closeObject

Closes the Browser



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/vapir-ie/browser.rb', line 312

def close
  assert_exists
  @browser_object.stop
  @browser_object.quit
  ::Waiter.try_for(config.close_timeout, :exception => WindowFailedToCloseException.new("The browser window did not close"), :interval => 1) do
    begin
      if exists?
        @browser_object.quit
        false
      else
        true
      end
    rescue WIN32OLERuntimeError, NoMethodError
      raise unless $!.message =~ ExistenceFailureCodesRE
      true
    end
  end
  @browser_object=nil
end

#close_modalObject

close modal dialog. unlike IE#modal_dialog.close, does not wait for dialog to appear and does not raise exception if no window is found. returns true if modal was found and close, otherwise false



25
26
27
28
29
30
# File 'lib/vapir-ie/close_all.rb', line 25

def close_modal
  modal_dialog=modal_dialog(:timeout => 0, :error => false)
  if modal_dialog && modal_dialog.exists?
    modal_dialog.close
  end
end

#close_othersObject

find other ie browser windows and close them



10
11
12
# File 'lib/vapir-ie/close_all.rb', line 10

def close_others
  IE.close_all_but self
end

#dirObject



387
388
389
# File 'lib/vapir-ie/browser.rb', line 387

def dir
  return File.expand_path(File.dirname(__FILE__))
end

#disable_checker(checker) ⇒ Object

this allows a checker to be disabled

  • checker Proc Object, the checker that is to be disabled



429
430
431
# File 'lib/vapir-ie/browser.rb', line 429

def disable_checker(checker)
  @error_checkers.delete(checker)
end

#documentObject Also known as: document_object

Return the current document



396
397
398
399
# File 'lib/vapir-ie/browser.rb', line 396

def document
  assert_exists
  return @browser_object.document
end

#element_object_by_xpath(xpath) ⇒ Object

return the first element object (not Element) that matches the xpath



646
647
648
649
# File 'lib/vapir-ie/browser.rb', line 646

def element_object_by_xpath(xpath)
  objects= element_objects_by_xpath(xpath)
  return (objects && objects[0])
end

#element_objects_by_xpath(xpath) ⇒ Object

execute xpath and return an array of elements



652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'lib/vapir-ie/browser.rb', line 652

def element_objects_by_xpath(xpath)
  doc = xmlparser_document_object 
  modifiedXpath = ""
  selectedElements = Array.new
  
  # strip any trailing slash from the xpath expression (as used in watir unit tests)
  xpath.chop! unless (/\/$/ =~ xpath).nil?
  
  doc.xpath(xpath).each do |element|
    modifiedXpath = element.path
    temp = element_by_absolute_xpath(modifiedXpath) # temp = a DOM/COM element
    selectedElements << temp if temp != nil
  end
  return selectedElements
end

#exists?Boolean Also known as: exist?

Are we attached to an open browser?

Returns:

  • (Boolean)


226
227
228
229
230
231
232
233
# File 'lib/vapir-ie/browser.rb', line 226

def exists?
  !!(@browser_object && begin
    @browser_object.name
  rescue WIN32OLERuntimeError, NoMethodError
    raise unless $!.message =~ ExistenceFailureCodesRE
    false
  end)
end

#focusObject

Gives focus to the frame



443
444
445
446
# File 'lib/vapir-ie/browser.rb', line 443

def focus
  document.activeElement.blur
  document.focus
end

#forwardObject

Go to the next page - the same as clicking the browsers forward button an WIN32OLERuntimeError exception is raised if the browser cant go forward



284
285
286
287
288
289
# File 'lib/vapir-ie/browser.rb', line 284

def forward
  assert_exists do
    @browser_object.GoForward
    wait
  end
end

#front?Boolean

Returns:

  • (Boolean)


352
353
354
# File 'lib/vapir-ie/browser.rb', line 352

def front?
  win_window.foreground?
end

#goto(url) ⇒ Object

Navigate to the specified URL.

* url - string - the URL to navigate to


265
266
267
268
269
270
271
# File 'lib/vapir-ie/browser.rb', line 265

def goto(url)
  assert_exists do
    @browser_object.navigate(url)
    wait
    return @down_load_time
  end
end

#hwndObject

Return the window handle of this browser



167
168
169
170
# File 'lib/vapir-ie/browser.rb', line 167

def hwnd
  assert_exists
  @hwnd ||= Vapir::IE.fix_win32ole_hwnd(@browser_object.HWND)
end

#killObject

kills this process. NOTE that this process may be running multiple browsers; killing the process will kill them all. use #close to close a single browser.



186
187
188
189
190
191
192
# File 'lib/vapir-ie/browser.rb', line 186

def kill
  # todo: drop win32api; use ffi 
  require 'Win32API'
  right_to_terminate_process = 1
  handle = Win32API.new('kernel32.dll', 'OpenProcess', 'lil', 'l').call(right_to_terminate_process, 0, process_id)
  Win32API.new('kernel32.dll', 'TerminateProcess', 'll', 'l').call(handle, 0)
end

#log(what) ⇒ Object



241
242
243
# File 'lib/vapir-ie/browser.rb', line 241

def log(what)
  @logger.debug(what) if @logger
end

#maximizeObject

Maximize the window (expands to fill the screen)



333
334
335
# File 'lib/vapir-ie/browser.rb', line 333

def maximize
  win_window.maximize!
end

#minimizeObject

Minimize the window (appears as icon on taskbar)



338
339
340
# File 'lib/vapir-ie/browser.rb', line 338

def minimize
  win_window.minimize!
end


199
200
201
202
203
204
205
# File 'lib/vapir-ie/browser.rb', line 199

def modal_dialog(options={})
  assert_exists do
    raise ArgumentError, "options argument must be a hash; received #{options.inspect} (#{options.class})" unless options.is_a?(Hash)
    modal=IE::ModalDialog.new(self, options.merge(:error => false))
    modal.exists? ? modal : nil
  end
end


207
208
209
210
211
# File 'lib/vapir-ie/browser.rb', line 207

def modal_dialog!(options={})
  assert_exists do
    IE::ModalDialog.new(self, options.merge(:error => true))
  end
end

#process_idObject

returns the process id of this browser



180
181
182
# File 'lib/vapir-ie/browser.rb', line 180

def process_id
  @process_id ||= win_window.process_id
end

#refreshObject

Refresh the current page - the same as clicking the browsers refresh button an WIN32OLERuntimeError exception is raised if the browser cant refresh



299
300
301
302
303
304
# File 'lib/vapir-ie/browser.rb', line 299

def refresh
  assert_exists do
    @browser_object.refresh2(RefreshConstants::REFRESH_COMPLETELY)
    wait
  end
end

#restoreObject

Restore the window (after minimizing or maximizing)



343
344
345
# File 'lib/vapir-ie/browser.rb', line 343

def restore
  win_window.restore!
end

#run_error_checksObject

this method runs the predefined error checks



415
416
417
418
419
# File 'lib/vapir-ie/browser.rb', line 415

def run_error_checks
  assert_exists do
    @error_checkers.each { |e| e.call(self) }
  end
end

#screen_capture(filename, options = {}) ⇒ Object

saves a screenshot of this browser window to the given filename.

the screenshot format is BMP (DIB), so you should name your files to end with .bmp

the last argument is an optional options hash, taking options:

  • :dc => (default is :window). may be one of:

    • :client takes a screenshot of the client area, which excludes the menu bar and other window trimmings.

    • :window (default) takes a screenshot of the full browser window

    • :desktop takes a screenshot of the full desktop



376
377
378
379
380
381
382
383
384
385
# File 'lib/vapir-ie/browser.rb', line 376

def screen_capture(filename, options = {})
  unless options.is_a?(Hash)
    dc = options
    options = {:dc => dc}
    if config.warn_deprecated
      Kernel.warn_with_caller("WARNING: The API for #screen_capture has changed and the last argument is now an options hash. Please change calls to this method to specify :dc => #{dc.inspect}")
    end
  end
  screen_capture_win_window(filename, options)
end

#send_keys(key_string) ⇒ Object

Send key events to IE window. See www.autoitscript.com/autoit3/docs/appendix/SendKeys.htm for complete documentation on keys supported and syntax.



359
360
361
362
363
364
365
# File 'lib/vapir-ie/browser.rb', line 359

def send_keys(key_string)
  assert_exists do
    require 'vapir-ie/autoit'
    bring_to_front
    Vapir.autoit.Send key_string
  end
end

#set_logger(logger) ⇒ Object

deprecated: use logger= instead



237
238
239
# File 'lib/vapir-ie/browser.rb', line 237

def set_logger(logger)
  @logger = logger
end

#show_activeObject

this method shows the name, id etc of the object that is currently active - ie the element that has focus its mostly used in irb when creating a script



435
436
437
438
439
440
# File 'lib/vapir-ie/browser.rb', line 435

def show_active # TODO/fix: move to common; test 
  
  current_object = document.activeElement
  current_element = base_class.factory(current_object)
  current_element.to_s
end

#statusObject

Return the status of the window, typically from the status bar at the bottom.



255
256
257
# File 'lib/vapir-ie/browser.rb', line 255

def status
  return @browser_object.statusText
end

#titleObject

Return the title of the document



250
251
252
# File 'lib/vapir-ie/browser.rb', line 250

def title
  @browser_object.document.title
end

#urlObject

returns the current url, as displayed in the address bar of the browser



407
408
409
410
# File 'lib/vapir-ie/browser.rb', line 407

def url
  assert_exists
  return @browser_object.LocationURL
end

#visibleObject



150
151
152
153
# File 'lib/vapir-ie/browser.rb', line 150

def visible
  assert_exists
  @browser_object.visible
end

#visible=(visibility) ⇒ Object



154
155
156
157
# File 'lib/vapir-ie/browser.rb', line 154

def visible=(visibility)
  assert_exists
  @browser_object.visible = visibility
end

#win_windowObject



194
195
196
197
# File 'lib/vapir-ie/browser.rb', line 194

def win_window
  Vapir.require_winwindow
  @win_window||= WinWindow.new(hwnd)
end

#xmlparser_document_objectObject

Functions written for using xpath for getting the elements.



450
451
452
453
454
455
# File 'lib/vapir-ie/browser.rb', line 450

def xmlparser_document_object
  if @xml_parser_doc == nil
    create_xml_parser_doc
  end
  return @xml_parser_doc
end