Class FireWatir::Firefox

  1. firewatir/lib/firewatir/firefox.rb
  2. firewatir/lib/firewatir/version.rb
  3. show all
Parent: Object

Included modules

  1. FireWatir::Container

Constants

FIRST_ORDERED_NODE_TYPE = 9   XPath Result type. Return only first node that matches the xpath expression. More details: “developer.mozilla.org/en/docs/DOM:document.evaluate
VERSION = '1.6.5'

Public class methods

attach (how, what)

Class method to return a browser object if a window matches for how and what. Window can be referenced by url or title. The second argument can be either a string or a regular expression. Watir::Browser.attach(:url, ‘www.google.com’) Watir::Browser.attach(:title, ‘Google’)

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 288
    def self.attach how, what
      br = new :suppress_launch_process => true # don't create window
      br.attach(how, what)
      br
    end
new (options = {})

TODO: Start the firefox version given by user.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 26
    def initialize(options = {})
      if (options.kind_of?(Integer))
        options = {:waitTime => options}
      end

      # check for jssh not running, firefox may be open but not with -jssh
      # if its not open at all, regardless of the :suppress_launch_process option start it
      # error if running without jssh, we don't want to kill their current window (mac only)
      jssh_down = false
      begin
        set_defaults()
      rescue Watir::Exception::UnableToStartJSShException
        jssh_down = true
      end

      if current_os == :macosx && !%x{ps x | grep firefox-bin | grep -v grep}.empty?
        raise "Firefox is running without -jssh" if jssh_down
        open_window unless options[:suppress_launch_process]
      elsif not options[:suppress_launch_process]
        launch_browser(options)
      end

      set_defaults()
      get_window_number()
      set_browser_document()
    end
start (url)

Creates a new instance of Firefox. Loads the URL and return the instance. Input:

url - url of the page to be loaded.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 80
    def self.start(url)
      ff = Firefox.new
      ff.goto(url)
      return ff
    end

Public instance methods

add_checker (checker)

Add an error checker that gets called on every page load.

  • checker - a Proc object
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 504
    def add_checker(checker)
      @error_checkers << checker
    end
attach (how, what)
Used for attaching pop up window to an existing Firefox window, either by url or title.
ff.attach(:url, 'http://www.google.com')
ff.attach(:title, 'Google')

Output:

Instance of newly attached window.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 269
    def attach(how, what)

      $stderr.puts("warning: #{self.class}.attach is experimental") if $VERBOSE
      window_number = find_window(how, what)

      if (window_number.nil?)
        raise NoMatchingWindowFoundException.new("Unable to locate window, using #{how} and #{what}")
      elsif (window_number >= 0)
        @window_index = window_number
        set_browser_document()
      end
      self
    end
back ()

Loads the previous page (if there is any) in the browser. Waits for the page to get loaded.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 119
    def back()
      js_eval "if(#{browser_var}.canGoBack) #{browser_var}.goBack()"
      wait()
    end
body_var (
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 214
    def body_var # unfinished
      "body"
    end
browser_var ()

private

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 206
    def browser_var
      "browser"
    end
close ()

Closes the window.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 220
    def close

      if js_eval("getWindows().length").to_i == 1
        js_eval("getWindows()[0].close()")

        if current_os == :macosx
          %x{ osascript -e 'tell application "Firefox" to quit' }
        end

        # wait for the app to close properly
        @t.join if @t
      else
        # Check if window exists, because there may be the case that it has been closed by click event on some element.
        # For e.g: Close Button, Close this Window link etc.
        window_number = find_window(:url, @window_url)

        # If matching window found. Close the window.
        if window_number > 0
          js_eval "getWindows()[#{window_number}].close()"
        end

      end
    end
close_all ()

Closes all firefox windows

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 245
    def close_all
      total_windows = js_eval("getWindows().length").to_i

      # start from last window
      while (total_windows > 0) do
        js_eval "getWindows()[#{total_windows - 1}].close()"
        total_windows = total_windows - 1
      end

      if current_os == :macosx
        %x{ osascript -e 'tell application "Firefox" to quit' }
      end

      if current_os == :windows
        system("taskkill /im Firefox.exe /f /t >nul 2>&1")
      end
    end
contains_text (target)

Description:

Matches the given text with the current text shown in the browser.

Input:

target - Text to match. Can be a string or regex

Output:

Returns the index if the specified text was found.
Returns matchdata object if the specified regexp was found.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 373
    def contains_text(target)
      #puts "Text to match is : #{match_text}"
      #puts "Html is : #{self.text}"
      case target
        when Regexp
          self.text.match(target)
        when String
          self.text.index(target)
        else
          raise TypeError, "Argument #{target} should be a string or regexp."
      end
    end
disable_checker (checker)

Disable an error checker

  • checker - a Proc object that is to be disabled
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 510
    def disable_checker(checker)
      @error_checkers.delete(checker)
    end
document ()

Returns the document element of the page currently loaded in the browser.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 626
    def document
      Document.new(self)
    end
document_var (
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 210
    def document_var # unfinished
      "document"
    end
element_by_xpath (xpath)

Returns the first element that matches the given xpath expression or query.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 631
    def element_by_xpath(xpath)
      temp = Element.new(nil, self)
      element_name = temp.element_by_xpath(self, xpath)
      return element_factory(element_name)
    end
elements_by_xpath (xpath)

Description:

Returns the array of elements that matches the xpath query.

Input:

Xpath expression or query.

Output:

Array of elements matching xpath query.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 726
    def elements_by_xpath(xpath)
      element = Element.new(nil, self)
      elem_names = element.elements_by_xpath(self, xpath)
      elem_names.inject([]) {|elements, name| elements << element_factory(name)}
    end
execute_script (source)

Executes the given JavaScript string

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 137
    def execute_script(source)
      result = js_eval source.to_s
      wait()

      result
    end
forward ()

Loads the next page (if there is any) in the browser. Waits for the page to get loaded.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 125
    def forward()
      js_eval "if(#{browser_var}.canGoForward) #{browser_var}.goForward()"
      wait()
    end
get_popup_text ()

Description:

Returns text of javascript pop up in case it comes.

Output:

Text shown in javascript pop up.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 618
    def get_popup_text()
      return_value = js_eval "popuptext"
      # reset the variable
      js_eval "popuptext = ''"
      return return_value
    end
goto (url)

Loads the given url in the browser. Waits for the page to get loaded.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 111
    def goto(url)
      get_window_number()
      set_browser_document()
      js_eval "#{browser_var}.loadURI(\"#{url}\")"
      wait()
    end
html ()

Returns the html of the page currently loaded in the browser.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 408
    def html
      result = js_eval("var htmlelem = #{document_var}.getElementsByTagName('html')[0]; htmlelem.innerHTML")
      return "<html>" + result + "</html>"
    end
inspect ()
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 53
    def inspect
      '#<%s:0x%x url=%s title=%s>' % [self.class, hash*2, url.inspect, title.inspect]
    end
maximize ()

Maximize the current browser window.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 419
    def maximize()
      js_eval "#{window_var}.maximize()"
    end
minimize ()

Minimize the current browser window.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 424
    def minimize()
      js_eval "#{window_var}.minimize()"
    end
refresh ()

Reloads the current page in the browser. Waits for the page to get loaded.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 131
    def refresh()
      js_eval "#{browser_var}.reload()"
      wait()
    end
run_error_checks ()

Run the predefined error checks. This is automatically called on every page load.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 515
    def run_error_checks
      @error_checkers.each { |e| e.call(self) }
    end
showDivs ()

Alias for show_divs

showForms ()

Alias for show_forms

showFrames ()

Alias for show_frames

showImages ()

Alias for show_images

showLabels ()

Alias for show_labels

showLinks ()

Alias for show_links

showPres ()

Alias for show_pres

showSpans ()

Alias for show_spans

showTables ()

Alias for show_tables

show_divs ()

Description:

Show all the divs available on the page.

Output:

Name, id, class and index of all the divs available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 804
    def show_divs
      divs = Document.new(self).get_divs
      puts "There are #{divs.length} divs"
      index = 1
      divs.each do |l|
        puts "div:   name: #{l.name}"
        puts "         id: #{l.id}"
        puts "      class: #{l.className}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_forms ()

Description:

Show all the forms available on the page.

Output:

Name, id, method and action of all the forms available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 739
    def show_forms
      forms = Document.new(self).get_forms()
      count = forms.length
      puts "There are #{count} forms"
      for i in 0..count - 1 do
        puts "Form name: " + forms[i].name
        puts "       id: " + forms[i].id
        puts "   method: " + forms[i].attribute_value("method")
        puts "   action: " + forms[i].action
      end
    end
show_frames ()

Description:

Show all the frames available on the page. Doesn't show nested frames.

Output:

Name, and index of all the frames available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 913
    def show_frames
      jssh_command = "var frameset = #{window_var}.frames;
                            var elements_frames = new Array();
                            for(var i = 0; i < frameset.length; i++)
                            {
                                var frames = frameset[i].frames;
                                for(var j = 0; j < frames.length; j++)
                                {
                                    elements_frames.push(frames[j].frameElement);
                                }
                            }
                            elements_frames.length;"

      length = js_eval(jssh_command).to_i

      puts "There are #{length} frames"

      frames = Array.new(length)
      for i in 0..length - 1 do
        frames[i] = Frame.new(self, :jssh_name, "elements_frames[#{i}]")
      end

      for i in 0..length - 1 do
        puts "frame: name: #{frames[i].name}"
        puts "      index: #{i+1}"
      end
    end
show_images ()

Description:

Show all the images available on the page.

Output:

Name, id, src and index of all the images available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 760
    def show_images
      images = Document.new(self).get_images
      puts "There are #{images.length} images"
      index = 1
      images.each do |l|
        puts "image: name: #{l.name}"
        puts "         id: #{l.id}"
        puts "        src: #{l.src}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_labels ()

Description:

Show all the labels available on the page.

Output:

Name, id, for and index of all the labels available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 891
    def show_labels
      labels = Document.new(self).get_labels
      puts "There are #{labels.length} labels"
      index = 1
      labels.each do |l|
        puts "label: name: #{l.name}"
        puts "         id: #{l.id}"
        puts "        for: #{l.for}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_links ()

Description:

Show all the links available on the page.

Output:

Name, id, href and index of all the links available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 782
    def show_links
      links = Document.new(self).get_links
      puts "There are #{links.length} links"
      index = 1
      links.each do |l|
        puts "link:  name: #{l.name}"
        puts "         id: #{l.id}"
        puts "       href: #{l.href}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_pres ()

Description:

Show all the pre elements available on the page.

Output:

Id, name and index of all the pre elements available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 848
    def show_pres
      pres = Document.new(self).get_pres
      puts "There are #{pres.length} pres"
      index = 1
      pres.each do |l|
        puts "pre:     id: #{l.id}"
        puts "       name: #{l.name}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_spans ()

Description:

Show all the spans available on the page.

Output:

Name, id, class and index of all the spans available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 869
    def show_spans
      spans = Document.new(self).get_spans
      puts "There are #{spans.length} spans"
      index = 1
      spans.each do |l|
        puts "span:  name: #{l.name}"
        puts "         id: #{l.id}"
        puts "      class: #{l.className}"
        puts "      index: #{index}"
        index += 1
      end
    end
show_tables ()

Description:

Show all the tables available on the page.

Output:

Id, row count, column count (only first row) and index of all the tables available on the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 826
    def show_tables
      tables = Document.new(self).get_tables
      puts "There are #{tables.length} tables"
      index = 1
      tables.each do |l|
        puts "table:   id: #{l.id}"
        puts "       rows: #{l.row_count}"
        puts "    columns: #{l.column_count}"
        puts "      index: #{index}"
        index += 1
      end
    end
startClicker (button, waitTime = 1, userInput = nil, text = nil)

Description:

Tells FireWatir to click javascript button in case one comes after performing some action on an element. Matches
text of pop up with one if supplied as parameter. If text matches clicks the button else stop script execution until
pop up is dismissed by manual intervention.

Input:

button      - JavaScript button to be clicked. Values can be OK or Cancel
waitTime    - Time to wait for pop up to come. Not used just for compatibility with Watir.
userInput   - Not used just for compatibility with Watir
text        - Text that should appear on pop up.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 555
    def startClicker(button, waitTime = 1, userInput = nil, text = nil)
      jssh_command = "var win = #{browser_var}.contentWindow;"
      if (button =~ /ok/i)
        jssh_command << "var popuptext = '';
                                 var old_alert = win.alert;
                                 var old_confirm = win.confirm;
                                 win.alert = function(param) {"
        if (text != nil)
          jssh_command <<          "if(param == \"#{text}\") {
                                                popuptext = param;
                                                return true;
                                              }
                                              else {
                                                popuptext = param;
                                                win.alert = old_alert;
                                                win.alert(param);
                                              }"
        else
          jssh_command <<          "popuptext = param; return true;"
        end
        jssh_command << "};
                                 win.confirm = function(param) {"
        if (text != nil)
          jssh_command <<          "if(param == \"#{text}\") {
                                                popuptext = param;
                                                return true;
                                              }
                                              else {
                                                win.confirm = old_confirm;
                                                win.confirm(param);
                                              }"
        else
          jssh_command <<          "popuptext = param; return true;"
        end
        jssh_command << "};"

      elsif (button =~ /cancel/i)
        jssh_command = "var old_confirm = win.confirm;
                                              win.confirm = function(param) {"
        if (text != nil)
          jssh_command <<          "if(param == \"#{text}\") {
                                                popuptext = param;
                                                return false;
                                              }
                                              else {
                                                win.confirm = old_confirm;
                                                win.confirm(param);
                                              }"
        else
          jssh_command <<          "popuptext = param; return false;"
        end
        jssh_command << "};"
      end
      js_eval jssh_command
    end
status ()
Returns the Status of the page currently loaded in the browser from statusbar.

Output:

Status of the page.
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 401
    def status
      js_status = js_eval("#{window_var}.status")
      js_status.empty? ? js_eval("#{window_var}.XULBrowserWindow.statusText;") : js_status
    end
text ()

Returns the text of the page currently loaded in the browser.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 414
    def text
      js_eval("#{body_var}.textContent").strip
    end
title ()

Returns the title of the page currently loaded in the browser.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 392
    def title
      @window_title = js_eval "#{document_var}.title"
    end
url ()

Returns the url of the page currently loaded in the browser.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 387
    def url
      @window_url = js_eval "#{document_var}.location"
    end
wait (last_url = nil)

Waits for the page to get loaded.

[show source]
# File firewatir/lib/firewatir/firefox.rb, line 429
    def wait(last_url = nil)
      #puts "In wait function "
      isLoadingDocument = ""
      start = Time.now

      while isLoadingDocument != "false"
        isLoadingDocument = js_eval("#{browser_var}=#{window_var}.getBrowser(); #{browser_var}.webProgress.isLoadingDocument;")
        #puts "Is browser still loading page: #{isLoadingDocument}"

        # Raise an exception if the page fails to load
        if (Time.now - start) > 300
          raise "Page Load Timeout"
        end
      end
      # If the redirect is to a download attachment that does not reload this page, this
      # method will loop forever. Therefore, we need to ensure that if this method is called
      # twice with the same URL, we simply accept that we're done.
      url = js_eval("#{browser_var}.contentDocument.URL")

      if (url != last_url)
        # Check for Javascript redirect. As we are connected to Firefox via JSSh. JSSh
        # doesn't detect any javascript redirects so check it here.
        # If page redirects to itself that this code will enter in infinite loop.
        # So we currently don't wait for such a page.
        # wait variable in JSSh tells if we should wait more for the page to get loaded
        # or continue. -1 means page is not redirected. Anyother positive values means wait.
        jssh_command = "var wait = -1; var meta = null; meta = #{browser_var}.contentDocument.getElementsByTagName('meta');
                                if(meta != null)
                                {
                                    var doc_url = #{browser_var}.contentDocument.URL;
                                    for(var i=0; i< meta.length;++i)
                                    {
                                                                          var content = meta[i].content;
                                                                         var regex = new RegExp(\"^refresh$\", \"i\");
                                                                        if(regex.test(meta[i].httpEquiv))
                                                                            {
                                                                                    var arrContent = content.split(';');
                                                                                var redirect_url = null;
                                                                               if(arrContent.length > 0)
                                                                              {
                                                                                     if(arrContent.length > 1)
                                                                                                    redirect_url = arrContent[1];

                                                                                         if(redirect_url != null)
                                                                                          {
                                                                                                regex = new RegExp(\"^.*\" + redirect_url + \"$\");
                                                                                               if(!regex.test(doc_url))
                                                                                              {
                                                                                                     wait = arrContent[0];
                                                                                                    }
                                                                                            }
                                                                                            break;
                                                                                    }
                                                                            }
                                                                    }
                                }
                                wait;"
        wait_time = js_eval(jssh_command).to_i
        begin
          if (wait_time != -1)
            sleep(wait_time)
            # Call wait again. In case there are multiple redirects.
            js_eval "#{browser_var} = #{window_var}.getBrowser()"
            wait(url)
          end
        rescue
        end
      end
      set_browser_document()
      run_error_checks()
      return self
    end
window_var ()
[show source]
# File firewatir/lib/firewatir/firefox.rb, line 201
    def window_var
      "window"
    end