Class: Watir::Browser

Inherits:
Object show all
Includes:
Container, HasWindow, 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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Waitable

#wait_until, #wait_until_present, #wait_while, #wait_while_present

Methods included from HasWindow

#original_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, #cursor, #cursors, #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, #div, #divs, #dl, #dls, #dt, #dts, #element, #elements, #ellipse, #ellipses, #em, #embed, #embeds, #ems, #extract_selector, #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, #hatchpath, #hatchpaths, #head, #header, #headers, #heads, #hidden, #hiddens, #hr, #hrs, #htmls, #i, #iframe, #iframes, #image, #images, #img, #imgs, #input, #inputs, #ins, #inses, #is, #kbd, #kbds, #keygen, #keygens, #label, #labels, #legend, #legends, #li, #line, #linear_gradient, #linear_gradients, #lines, #link, #links, #lis, #main, #mains, #map, #maps, #mark, #marker, #markers, #marks, #menu, #menuitem, #menuitems, #menus, #mesh, #meshes, #meshgradient, #meshgradients, #meshpatch, #meshpatches, #meshrow, #meshrows, #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, #solidcolor, #solidcolors, #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 XpathSupport

downcase, escape

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



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

def initialize(browser = :chrome, *args)
  case browser
  when ::Symbol, String
    selenium_args = Watir::Capabilities.new(browser, *args).to_args
    @driver = Selenium::WebDriver.for *selenium_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



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

def after_hooks
  @after_hooks
end

#default_context=(value) ⇒ Object (writeonly)

Sets the attribute default_context

Parameters:

  • value

    the value to set the attribute default_context to.



12
13
14
# File 'lib/watir/browser.rb', line 12

def default_context=(value)
  @default_context = value
end

#driverObject (readonly) Also known as: wd

Returns the value of attribute driver



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

def driver
  @driver
end

#original_window=(value) ⇒ Object (writeonly)

Sets the attribute original_window

Parameters:

  • value

    the value to set the attribute original_window to.



12
13
14
# File 'lib/watir/browser.rb', line 12

def original_window=(value)
  @original_window = value
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:



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

def start(url, browser = :chrome, *args)
  b = new(browser, *args)
  b.goto url

  b
end

Instance Method Details

#alertWatir::Alert

Handles JavaScript alerts, confirms and prompts.

Returns:



200
201
202
# File 'lib/watir/browser.rb', line 200

def alert
  Alert.new(self)
end

#assert_existsObject

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.

Protocol shared with Watir::Element



311
312
313
314
315
# File 'lib/watir/browser.rb', line 311

def assert_exists
  ensure_context
  return if window.present?
  raise Exception::NoMatchingWindowFoundException, "browser window was closed"
end

#backObject

Navigates back in history.



92
93
94
95
# File 'lib/watir/browser.rb', line 92

def back
  @driver.navigate.back
  @after_hooks.run
end

#browserObject



323
324
325
# File 'lib/watir/browser.rb', line 323

def browser
  self
end

#closeObject Also known as: quit

Closes browser.



141
142
143
144
145
# File 'lib/watir/browser.rb', line 141

def close
  return if @closed
  @driver.quit
  @closed = true
end

#cookiesWatir::Cookies

Handles cookies.

Returns:



154
155
156
# File 'lib/watir/browser.rb', line 154

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

#ensure_contextObject

Raises:



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

def ensure_context
  raise Exception::Error, "browser was closed" if @closed
  driver.switch_to.default_content unless @default_context
  @default_context = true
end

#execute_script(script, *args) ⇒ 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



263
264
265
266
267
268
# File 'lib/watir/browser.rb', line 263

def execute_script(script, *args)
  args.map! { |e| e.kind_of?(Watir::Element) ? e.wd : e }
  returned = @driver.execute_script(script, *args)

  wrap_elements_in(self, returned)
end

#exist?Boolean Also known as: exists?

Returns true if browser is not closed and false otherwise.

Returns:

  • (Boolean)


300
301
302
# File 'lib/watir/browser.rb', line 300

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

#forwardObject

Navigates forward in history.



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

def forward
  @driver.navigate.forward
  @after_hooks.run
end

#goto(uri) ⇒ String

Goes to the given URL.

Examples:

browser.goto "watir.github.io"

Parameters:

  • uri (String)

    The url.

Returns:

  • (String)

    The url you end up at.



79
80
81
82
83
84
85
86
# File 'lib/watir/browser.rb', line 79

def goto(uri)
  uri = "http://#{uri}" unless uri =~ URI.regexp

  @driver.navigate.to uri
  @after_hooks.run

  uri
end

#htmlString

Returns HTML code of current page.

Returns:

  • (String)


189
190
191
192
# File 'lib/watir/browser.rb', line 189

def html
  # use body.html instead?
  @driver.page_source
end

#inspectObject Also known as: selector_string



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

def inspect
  '#<%s:0x%x url=%s title=%s>' % [self.class, hash*2, url.inspect, title.inspect]
rescue Errno::ECONNREFUSED
  '#<%s:0x%x closed=true>' % [self.class, hash*2]
rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError
  '#<%s:0x%x alert=true>' % [self.class, hash*2]
end

#nameSymbol

Returns browser name.

Examples:

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

Returns:



169
170
171
# File 'lib/watir/browser.rb', line 169

def name
  @driver.browser
end

#ready_stateString

Returns readyState of document.

Returns:

  • (String)


235
236
237
# File 'lib/watir/browser.rb', line 235

def ready_state
  execute_script 'return document.readyState'
end

#refreshObject

Refreshes current page.



208
209
210
211
# File 'lib/watir/browser.rb', line 208

def refresh
  @driver.navigate.refresh
  @after_hooks.run
end

#screenshotWatir::Screenshot

Handles screenshots of current pages.

Returns:



290
291
292
# File 'lib/watir/browser.rb', line 290

def screenshot
  Screenshot.new driver
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:



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

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

#statusString

Returns the text of status bar.

Returns:

  • (String)


245
246
247
# File 'lib/watir/browser.rb', line 245

def status
  execute_script "return window.status;"
end

#textString

Returns text of page body.

Returns:

  • (String)


179
180
181
# File 'lib/watir/browser.rb', line 179

def text
  body.text
end

#titleString

Returns title of current page.

Examples:

browser.goto "watir.github.io"
browser.title
#=> "Watir is... – Watir Project – Watir stands for Web Application Testing In Ruby. It facilitates the writing of automated tests by mimicking the behavior of a user interacting with a website."

Returns:

  • (String)


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

def title
  @driver.title
end

#urlString

Returns URL of current page.

Examples:

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

Returns:

  • (String)


117
118
119
120
# File 'lib/watir/browser.rb', line 117

def url
  assert_exists
  @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:



223
224
225
226
227
# File 'lib/watir/browser.rb', line 223

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