Class: Watir::Browser

Inherits:
Object
  • Object
show all
Includes:
Container, Exception, HasWindow, Navigation, Scrolling, Waitable
Defined in:
lib/watir/browser.rb,
lib/watir/extensions/nokogiri.rb

Overview

The main class through which you control the browser.

Instance Attribute Summary collapse

Attributes included from HasWindow

#original_window

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Scrolling

#scroll

Methods included from Navigation

#back, #forward, #goto, #refresh

Methods included from Waitable

#wait_until, #wait_while

Methods included from HasWindow

#switch_window, #window, #windows

Methods included from Container

#a, #abbr, #abbrs, #address, #addresses, #area, #areas, #article, #articles, #as, #aside, #asides, #audio, #audios, #b, #base, #bases, #bdi, #bdis, #bdo, #bdos, #blockquote, #blockquotes, #body, #bodys, #br, #brs, #bs, #button, #buttons, #canvas, #canvases, #caption, #captions, #checkbox, #checkboxes, #circle, #circles, #cite, #cites, #code, #codes, #col, #colgroup, #colgroups, #cols, #data, #datalist, #datalists, #datas, #date_field, #date_fields, #date_time_field, #date_time_fields, #dd, #dds, #defs, #defss, #del, #dels, #desc, #descs, #details, #detailses, #dfn, #dfns, #dialog, #dialogs, #div, #divs, #dl, #dls, #dt, #dts, #element, #elements, #ellipse, #ellipses, #em, #embed, #embeds, #ems, #field_set, #field_sets, #fieldset, #fieldsets, #figcaption, #figcaptions, #figure, #figures, #file_field, #file_fields, #font, #fonts, #footer, #footers, #foreign_object, #foreign_objects, #form, #forms, #frame, #frames, #frameset, #framesets, #g, #gs, #h1, #h1s, #h2, #h2s, #h3, #h3s, #h4, #h4s, #h5, #h5s, #h6, #h6s, #head, #header, #headers, #heads, #hidden, #hiddens, #hr, #hrs, #htmls, #i, #iframe, #iframes, #image, #images, #img, #imgs, #input, #inputs, #ins, #inses, #is, #kbd, #kbds, #label, #labels, #legend, #legends, #li, #line, #linear_gradient, #linear_gradients, #lines, #link, #links, #lis, #main, #mains, #map, #maps, #mark, #marker, #markers, #marks, #meta, #metadata, #metadatas, #metas, #meter, #meters, #nav, #navs, #noscript, #noscripts, #object, #objects, #ol, #ols, #optgroup, #optgroups, #option, #options, #output, #outputs, #p, #param, #params, #path, #paths, #pattern, #patterns, #picture, #pictures, #polygon, #polygons, #polyline, #polylines, #pre, #pres, #progress, #progresses, #ps, #q, #qs, #radial_gradient, #radial_gradients, #radio, #radio_set, #radios, #rb, #rbs, #rect, #rects, #rp, #rps, #rt, #rtc, #rtcs, #rts, #rubies, #ruby, #s, #samp, #samps, #script, #scripts, #section, #sections, #select, #select_list, #select_lists, #selects, #small, #smalls, #source, #sources, #span, #spans, #ss, #stop, #stops, #strong, #strongs, #style, #styles, #sub, #subs, #summaries, #summary, #sup, #sups, #svg, #svgs, #switch, #switches, #symbol, #symbols, #table, #tables, #tbody, #tbodys, #td, #tds, #template, #templates, #text_field, #text_fields, #text_path, #text_paths, #textarea, #textareas, #tfoot, #tfoots, #th, #thead, #theads, #ths, #time, #times, #titles, #tr, #track, #tracks, #trs, #tspan, #tspans, #u, #ul, #uls, #us, #use, #uses, #var, #vars, #video, #videos, #view, #views, #wbr, #wbrs

Methods included from JSSnippets

#execute_js

Constructor Details

#initialize(browser = :chrome, *args) ⇒ Browser

Creates a Watir::Browser instance.

Parameters:

  • browser (Symbol, Selenium::WebDriver) (defaults to: :chrome)

    :firefox, :ie, :chrome, :remote or Selenium::WebDriver instance

  • args

    Passed to the underlying driver


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/watir/browser.rb', line 42

def initialize(browser = :chrome, *args)
  case browser
  when ::Symbol, String
    @capabilities = Capabilities.new(browser, *args)
    @driver = Selenium::WebDriver.for(*@capabilities.to_args)
  when Selenium::WebDriver::Driver
    @driver = browser
  else
    raise ArgumentError, "expected Symbol or Selenium::WebDriver::Driver, got #{browser.class}"
  end

  @after_hooks = AfterHooks.new(self)
  @closed = false
  @default_context = true
end

Instance Attribute Details

#after_hooksObject (readonly)

Returns the value of attribute after_hooks.


15
16
17
# File 'lib/watir/browser.rb', line 15

def after_hooks
  @after_hooks
end

#capabilitiesObject (readonly)

Returns the value of attribute capabilities.


15
16
17
# File 'lib/watir/browser.rb', line 15

def capabilities
  @capabilities
end

#default_context=(value) ⇒ Object (writeonly)

Sets the attribute default_context

Parameters:

  • value

    the value to set the attribute default_context to.


14
15
16
# File 'lib/watir/browser.rb', line 14

def default_context=(value)
  @default_context = value
end

#driverObject (readonly) Also known as: wd

Returns the value of attribute driver.


15
16
17
# File 'lib/watir/browser.rb', line 15

def driver
  @driver
end

#locator_namespaceObject

Whether the locators should be used from a different namespace. Defaults to Watir::Locators.


296
297
298
# File 'lib/watir/browser.rb', line 296

def locator_namespace
  @locator_namespace ||= Locators
end

#original_window=(value) ⇒ Object (writeonly)

Sets the attribute original_window

Parameters:

  • value

    the value to set the attribute original_window to.


14
15
16
# File 'lib/watir/browser.rb', line 14

def original_window=(value)
  @original_window = value
end

#timerObject


317
318
319
# File 'lib/watir/browser.rb', line 317

def timer
  @timer ||= Wait::Timer.new
end

Class Method Details

.start(url, browser = :chrome, *args) ⇒ Watir::Browser

Creates a Watir::Browser instance and goes to URL.

Examples:

browser = Watir::Browser.start "www.google.com", :chrome
#=> #<Watir::Browser:0x..fa45a499cb41e1752 url="http://www.google.com" title="Google">

Parameters:

  • url (String)
  • browser (Symbol, Selenium::WebDriver) (defaults to: :chrome)

    :firefox, :ie, :chrome, :remote or Selenium::WebDriver instance

Returns:


30
31
32
# File 'lib/watir/browser.rb', line 30

def start(url, browser = :chrome, *args)
  new(browser, *args).tap { |b| b.goto url }
end

Instance Method Details

#alertWatir::Alert

Handles JavaScript alerts, confirms and prompts.

Returns:


177
178
179
# File 'lib/watir/browser.rb', line 177

def alert
  Alert.new(self)
end

#browserObject


287
288
289
# File 'lib/watir/browser.rb', line 287

def browser
  self
end

#closeObject Also known as: quit

Closes browser.


108
109
110
111
112
113
# File 'lib/watir/browser.rb', line 108

def close
  return if closed?

  @driver.quit
  @closed = true
end

#closed?Boolean

Returns true if browser is closed and false otherwise.

Returns:

  • (Boolean)

122
123
124
# File 'lib/watir/browser.rb', line 122

def closed?
  @closed
end

#cookiesWatir::Cookies

Handles cookies.

Returns:


132
133
134
# File 'lib/watir/browser.rb', line 132

def cookies
  @cookies ||= Cookies.new driver.manage
end

#ensure_contextObject


280
281
282
283
284
285
# File 'lib/watir/browser.rb', line 280

def ensure_context
  return if @default_context

  driver.switch_to.default_content
  @default_context = true
end

#execute_script(script, *args, function_name: nil) ⇒ Object

Executes JavaScript snippet.

If you are going to use the value snippet returns, make sure to use `return` explicitly.

Examples:

Check that Ajax requests are completed with jQuery

browser.execute_script("return jQuery.active") == 0
#=> true

Parameters:

  • script (String)

    JavaScript snippet to execute

  • args

    Arguments will be available in the given script in the 'arguments' pseudo-array


231
232
233
234
235
236
237
# File 'lib/watir/browser.rb', line 231

def execute_script(script, *args, function_name: nil)
  args.map! do |e|
    e.is_a?(Element) ? e.wait_until(&:exists?).wd : e
  end
  Watir.logger.info "Executing Script on Browser: #{function_name}" if function_name
  wrap_elements_in(self, @driver.execute_script(script, *args))
end

#exist?Boolean Also known as: exists?

Returns true if browser is not closed and false otherwise.

Returns:

  • (Boolean)

269
270
271
# File 'lib/watir/browser.rb', line 269

def exist?
  !closed? && window.present?
end

#htmlString

Returns HTML code of current page.

Returns:

  • (String)

167
168
169
# File 'lib/watir/browser.rb', line 167

def html
  @driver.page_source
end

#inspectObject Also known as: selector_string

rubocop:disable Metrics/AbcSize TODO: w3c default behavior does not like checking if alert exists


60
61
62
63
64
65
66
67
68
69
70
# File 'lib/watir/browser.rb', line 60

def inspect
  if alert.exists?
    format('#<%s:0x%x alert=true>', self.class, hash * 2)
  else
    format('#<%s:0x%x url=%s title=%s>', self.class, hash * 2, url.inspect, title.inspect)
  end
rescue Selenium::WebDriver::Error::NoSuchWindowError
  format('#<%s:0x%x closed=%s>', self.class, hash * 2, closed?)
rescue Errno::ECONNREFUSED
  format('#<%s:0x%x closed=true>', self.class, hash * 2)
end

#locateObject

Raises:


274
275
276
277
278
# File 'lib/watir/browser.rb', line 274

def locate
  raise Error, 'browser was closed' if closed?

  ensure_context
end

#nameSymbol

Returns browser name.

Examples:

browser = Watir::Browser.new :chrome
browser.name
#=> :chrome

Returns:


147
148
149
# File 'lib/watir/browser.rb', line 147

def name
  @driver.browser
end

#ready_stateString

Returns readyState of document.

Returns:

  • (String)

203
204
205
# File 'lib/watir/browser.rb', line 203

def ready_state
  execute_script 'return document.readyState'
end

#screenshotWatir::Screenshot

Handles screenshots of current pages.

Returns:


259
260
261
# File 'lib/watir/browser.rb', line 259

def screenshot
  Screenshot.new self
end

#send_keys(*args) ⇒ Object

Sends sequence of keystrokes to currently active element.

Examples:

browser.goto "www.google.com"
browser.send_keys "Watir", :return

Parameters:


249
250
251
# File 'lib/watir/browser.rb', line 249

def send_keys(*args)
  @driver.switch_to.active_element.send_keys(*args)
end

#statusString

Returns the text of status bar.

Returns:

  • (String)

213
214
215
# File 'lib/watir/browser.rb', line 213

def status
  execute_script 'return window.status;'
end

#textString

Returns text of page body.

Returns:

  • (String)

157
158
159
# File 'lib/watir/browser.rb', line 157

def text
  body.text
end

#titleString

Returns title of current page.

Examples:

browser.goto "watir.github.io"
browser.title
#=> "Watir Project"

Returns:

  • (String)

100
101
102
# File 'lib/watir/browser.rb', line 100

def title
  @driver.title
end

#urlString

Returns URL of current page.

Examples:

browser.goto "watir.com"
browser.url
#=> "http://watir.com/"

Returns:

  • (String)

85
86
87
# File 'lib/watir/browser.rb', line 85

def url
  @driver.current_url
end

#wait(timeout = 5) ⇒ Object

Waits until readyState of document is complete.

Examples:

browser.wait

Parameters:

  • timeout (Integer) (defaults to: 5)

Raises:


191
192
193
194
195
# File 'lib/watir/browser.rb', line 191

def wait(timeout = 5)
  wait_until(timeout: timeout, message: "waiting for document.readyState == 'complete'") do
    ready_state == 'complete'
  end
end

#wrap_elements_in(scope, obj) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/watir/browser.rb', line 304

def wrap_elements_in(scope, obj)
  case obj
  when Selenium::WebDriver::Element
    wrap_element(scope, obj)
  when Array
    obj.map { |e| wrap_elements_in(scope, e) }
  when Hash
    obj.each { |k, v| obj[k] = wrap_elements_in(scope, v) }
  else
    obj
  end
end