Class: FireWatir::Element

Inherits:
Object
  • Object
show all
Includes:
Container
Defined in:
lib/firewatir/element.rb

Overview

Base class for html elements. This is not a class that users would normally access.

Constant Summary collapse

TO_S_SIZE =

Number of spaces that separate the property from the value in the to_s method

14
ORDERED_NODE_ITERATOR_TYPE =

How to get the nodes using XPath in mozilla.

5
NUMBER_TYPE =

To get the number of nodes returned by the xpath expression

1
FIRST_ORDERED_NODE_TYPE =

To get single node value

9
@@current_level =

This stores the level to which we have gone finding element inside another element. This is just to make sure that every element has unique name in JSSH.

0

Constants included from Container

Container::DEFAULT_HIGHLIGHT_COLOR, Container::MACHINE_IP

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Container

#button, #cell, #checkbox, #dd, #dl, #dt, #file_field, #form, #frame, #hidden, #image, #link, #radio, #row, #select_list, #show_all_objects, #table, #text_field

Methods included from JsshSocket

#js_eval, #js_eval_method, #jssh_socket, #read_socket

Constructor Details

#initialize(element, container = nil) ⇒ Element

Description:

Creates new instance of element. If argument is not nil and is of type string this
sets the element_name and element_type property of the object. These properties can
be accessed using element_object and element_type methods respectively.

Used internally by FireWatir.

Input:

element - Name of the variable with which the element is referenced in JSSh.


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/firewatir/element.rb', line 33

def initialize(element, container=nil)
  @container = container
  @element_name = element
  @element_type = element_type
  #puts "in initialize "
  #puts caller(0)
  #if(element != nil && element.class == String)
  #@element_name = element
  #elsif(element != nil && element.class == Element)
  #    @o = element
  #end

  #puts "@element_name is #{@element_name}"
  #puts "@element_type is #{@element_type}"
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(methId, *args) ⇒ Object

Description:

Traps all the function calls for an element that is not defined and fires them again
as it is to the jssh. This can be used in case the element supports properties or methods
that are not defined in the corresponding element class or in the base class(Element).

Input:

methodId - Id of the method that is called.
*args - arguments sent to the methods.


1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'lib/firewatir/element.rb', line 1267

def method_missing(methId, *args)
  methodName = methId.id2name
  #puts "method name is : #{methodName}"
  assert_exists
  #assert_enabled
  methodName = "colSpan" if methodName == "colspan"
  if(methodName =~ /invoke/)
    jssh_command = "#{element_object}."
    for i in args do
      jssh_command << i;
    end
    #puts "#{jssh_command}"
    jssh_socket.send("#{jssh_command};\n", 0)
    return_value = read_socket()
    #puts "return value is : #{return_value}"
    return return_value
  else
    #assert_exists
    #puts "element name is #{element_object}"

    # We get method name with trailing '=' when we try to assign a value to a
    # property. So just remove the '=' to get the type
    temp = ""
    assigning_value = false
    if(methodName =~ /(.*)=$/)
      temp  = "#{element_object}.#{$1}"
      assigning_value = true
    else
      temp = "#{element_object}.#{methodName}"
    end
    #puts "temp is : #{temp}"

    jssh_socket.send("typeof(#{temp});\n", 0)
    method_type = read_socket()
    #puts "method_type is : #{method_type}"

    if(assigning_value)
      if(method_type != "boolean" && args[0].class != Fixnum)
        args[0].gsub!("\\", "\\"*4)
        args[0].gsub!("\"", "\\\"")
        args[0].gsub!("\n","\\n")
        jssh_command = "#{element_object}.#{methodName}\"#{args[0]}\""
      else
        jssh_command = "#{element_object}.#{methodName}#{args[0]}"
      end
      #puts "jssh_command is : #{jssh_command}"
      jssh_socket.send("#{jssh_command};\n", 0)
      read_socket()
      return
    end

    methodName = "#{element_object}.#{methodName}"
    if(args.length == 0)
      #puts "In if loop #{methodName}"
      if(method_type == "function")
        jssh_command =  "#{methodName}();\n"
      else
        jssh_command =  "#{methodName};\n"
      end
    else
      #puts "In else loop : #{methodName}"
      jssh_command =  "#{methodName}("

      count = 0
      if args != nil
        for i in args
          jssh_command << "," if count != 0
          if i.kind_of? Numeric
            jssh_command << i.to_s
          else
            jssh_command << "\"#{i.to_s.gsub(/"/,"\\\"")}\""
          end
          count = count + 1
        end
      end

      jssh_command << ");\n"
    end

    if(method_type == "boolean")
      jssh_command = jssh_command.gsub("\"false\"", "false")
      jssh_command = jssh_command.gsub("\"true\"", "true")
    end
    #puts "jssh_command is #{jssh_command}"
    jssh_socket.send("#{jssh_command}", 0)
    returnValue = read_socket()
    #puts "return value is : #{returnValue}"

    @@current_level = 0

    if(method_type == "boolean")
      return false if(returnValue == "false")
      return true if(returnValue == "true")
    elsif(method_type == "number")
      return returnValue.to_i
    else
      return returnValue
    end
  end
end

Instance Attribute Details

#element_nameObject

This stores the name of the element that is about to trigger an Javascript pop up. @@current_js_object = nil



21
22
23
# File 'lib/firewatir/element.rb', line 21

def element_name
  @element_name
end

Instance Method Details

#assert_enabledObject

Description:

Checks if element is enabled or not. Raises ObjectDisabledException if object is disabled and
you are trying to use the object.


920
921
922
923
924
# File 'lib/firewatir/element.rb', line 920

def assert_enabled
  unless enabled?
    raise ObjectDisabledException, "object #{@how} and #{@what} is disabled"
  end
end

#assert_existsObject

Description:

Checks if element exists or not. Raises UnknownObjectException if element doesn't exists.


908
909
910
911
912
913
# File 'lib/firewatir/element.rb', line 908

def assert_exists
  unless exists?
    raise UnknownObjectException.new(
                                     Watir::Exception.message_for_unable_to_locate(@how, @what))
  end
end

#attribute_value(attribute_name) ⇒ Object

Description:

Returns the value of the specified attribute of an element.


896
897
898
899
900
901
902
# File 'lib/firewatir/element.rb', line 896

def attribute_value(attribute_name)
  #puts attribute_name
  assert_exists()
  return_value = get_attribute_value(attribute_name)
  @@current_level = 0
  return return_value
end

#clickObject

Description:

Function to fire click event on elements.


1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/firewatir/element.rb', line 1069

def click
  assert_exists
  assert_enabled

  highlight(:set)
  #puts "#{element_object} and #{element_type}"
  case element_type

    when "HTMLAnchorElement", "HTMLImageElement"
    # Special check for link or anchor tag. Because click() doesn't work on links.
    # More info: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-48250443
    # https://bugzilla.mozilla.org/show_bug.cgi?id=148585

    jssh_command = "var event = #{@container.document_var}.createEvent(\"MouseEvents\");"

    # Info about initMouseEvent at: http://www.xulplanet.com/references/objref/MouseEvent.html
    jssh_command << "event.initMouseEvent('click',true,true,null,1,0,0,0,0,false,false,false,false,0,null);"
    jssh_command << "#{element_object}.dispatchEvent(event);\n"

    #puts "jssh_command is: #{jssh_command}"
    jssh_socket.send("#{jssh_command}", 0)
    read_socket()
  else
    jssh_socket.send("typeof(#{element_object}.click);\n", 0)
    isDefined = read_socket()
    if(isDefined == "undefined")
      fire_event("onclick")
    else
      jssh_socket.send("#{element_object}.click();\n" , 0)
      read_socket()
    end
  end
  highlight(:clear)
  # Wait for firefox to reload.
  wait()
end

#contains_text(target) ⇒ Object

Description:

Matches the given text with the current text shown in the browser for that particular element.

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.


678
679
680
681
682
683
684
685
686
687
688
# File 'lib/firewatir/element.rb', line 678

def contains_text(target)
  #puts "Text to match is : #{match_text}"
  #puts "Html is : #{self.text}"
  if target.kind_of? Regexp
    self.text.match(target)
  elsif target.kind_of? String
    self.text.index(target)
  else
    raise TypeError, "Argument #{target} should be a string or regexp."
  end
end

#disabledObject Also known as: disabled?

Returns whether the element is disabled



1012
1013
1014
# File 'lib/firewatir/element.rb', line 1012

def disabled
  ! enabled?
end

#document_varObject

Description:

Document var.  Unfinished.


1110
1111
1112
# File 'lib/firewatir/element.rb', line 1110

def document_var
  "document"
end

#element_by_xpath(container, xpath) ⇒ Object

Description:

Returns first element found while traversing the DOM; that matches an given XPath query.
Mozilla browser directly supports XPath query on its DOM. So no need to create the DOM tree as WATiR does for IE.
Refer: http://developer.mozilla.org/en/docs/DOM:document.evaluate
Used internally by Firewatir use ff.element_by_xpath instead.

Input:

xpath - The xpath expression or query.

Output:

First element in DOM that matched the XPath expression or query.


755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'lib/firewatir/element.rb', line 755

def element_by_xpath(container, xpath)
  #puts "here locating element by xpath"
  rand_no = rand(1000)
  xpath.gsub!("\"", "\\\"")
  jssh_command = "var element_xpath_#{rand_no} = null; element_xpath_#{rand_no} = #{@container.document_var}.evaluate(\"#{xpath}\", #{container.document_var}, null, #{FIRST_ORDERED_NODE_TYPE}, null).singleNodeValue; element_xpath_#{rand_no};"

  jssh_socket.send("#{jssh_command}\n", 0)
  result = read_socket()
  #puts "command send to jssh is : #{jssh_command}"
  #puts "result is : #{result}"
  if(result == "null" || result == "" || result.include?("exception"))
    @@current_level = 0
    return nil
  else
    @@current_level += 1
    return "element_xpath_#{rand_no}"
  end
end

#element_typeObject

Description:

Returns the type of element. For e.g.: HTMLAnchorElement. used internally by Firewatir

Output:

Type of the element.


802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
# File 'lib/firewatir/element.rb', line 802

def element_type
  #puts "in element_type object is : #{element_object}"
  # Get the type of the element.
  jssh_socket.send("#{element_object};\n", 0)
  temp = read_socket()

  #puts "#{element_object} and type is #{temp}"
  temp =~ /\[object\s(.*)\]/
  if $1
    return $1
  else
    # This is done because in JSSh if you write element name of anchor type
    # then it displays the link to which it navigates instead of displaying
    # object type. So above regex match will return nil
    return "HTMLAnchorElement"
  end
end

#elements_by_xpath(container, xpath) ⇒ Object

Description:

Returns array of elements that matches a given XPath query.
Mozilla browser directly supports XPath query on its DOM. So no need to create the DOM tree as WATiR does for IE.
Refer: http://developer.mozilla.org/en/docs/DOM:document.evaluate
Used internally by Firewatir use ff.elements_by_xpath instead.

Input:

xpath - The xpath expression or query.

Output:

Array of elements that matched the xpath expression provided as parameter.


708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
# File 'lib/firewatir/element.rb', line 708

def elements_by_xpath(container, xpath)
  rand_no = rand(1000)
  #jssh_command = "var xpathResult = document.evaluate(\"count(#{xpath})\", document, null, #{NUMBER_TYPE}, null); xpathResult.numberValue;"
  #jssh_socket.send("#{jssh_command}\n", 0);
  #node_count = read_socket()
  xpath.gsub!("\"", "\\\"")
  jssh_command = "var element_xpath_#{rand_no} = new Array();"

  jssh_command << "var result = #{@container.document_var}.evaluate(\"#{xpath}\", #{@container.document_var}, null, #{ORDERED_NODE_ITERATOR_TYPE}, null);
                           var iterate = result.iterateNext();
                           while(iterate)
                           {
                              element_xpath_#{rand_no}.push(iterate);
                              iterate = result.iterateNext();
                           }
                           element_xpath_#{rand_no}.length;
                           "

  # Remove \n that are there in the string as a result of pressing enter while formatting.
  jssh_command.gsub!(/\n/, "")
  #puts jssh_command
  jssh_socket.send("#{jssh_command};\n", 0)
  node_count = read_socket()
  #puts "value of count is : #{node_count}"

  elements = Array.new(node_count.to_i)

  for i in 0..elements.length - 1 do
    elements[i] = "element_xpath_#{rand_no}[#{i}]"
  end

  return elements;
end

#enabled?Boolean

Description:

First checks if element exists or not. Then checks if element is enabled or not.

Output:

Returns true if element exists and is enabled, else returns false.

Returns:

  • (Boolean)


933
934
935
936
937
938
939
940
# File 'lib/firewatir/element.rb', line 933

def enabled?
  assert_exists
  value = js_eval_method "disabled"
  @@current_level = 0
  return true if(value == "false")
  return false if(value == "true")
  return value
end

#exists?Boolean Also known as: exist?

Description:

Checks if element exists or not. If element is not located yet then first locates the element.

Output:

True if element exists, false otherwise.

Returns:

  • (Boolean)


961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'lib/firewatir/element.rb', line 961

def exists?
  # puts "element is : #{element_object}"
  # puts caller(0)
  # If elements array has changed locate the element again. So that the element name points to correct element.
  if(element_object == nil || element_object == "")
    @@current_level = 0
    #puts "locating element"
    locate if respond_to?(:locate)
    if(@element_name == nil || @element_name == "")
      return false
    else
      #puts caller(0)
      #puts "element name is : #{@element_name}"
      return true
    end
  else
    #puts "not locating the element again"
    return true
  end
  #@@current_level = 0
  #if(element_object == nil || element_object == "")
  #    return false
  #else
  #    return true
  #end
rescue UnknownFrameException
  false
end

#fire_event(event, wait = true) ⇒ Object Also known as: fireEvent

Description:

Fires the provided event for an element and by default waits for the action to get completed.

Input:

event - Event to be fired like "onclick", "onchange" etc.
wait - Whether to wait for the action to get completed or not. By default its true.

TODO: Provide ability to specify event parameters like keycode for key events, and click screen

coordinates for mouse events.


831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
# File 'lib/firewatir/element.rb', line 831

def fire_event(event, wait = true)
  assert_exists()
  event = event.to_s # in case event was given as a symbol

  event = event.downcase

  event =~ /on(.*)/i
  event = $1 if $1

  # check if we've got an old-school on-event
  #jssh_socket.send("typeof(#{element_object}.#{event});\n", 0)
  #is_defined = read_socket()

  # info about event types harvested from:
  #   http://www.howtocreate.co.uk/tutorials/javascript/domevents
  case event
    when 'abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize',
                  'scroll', 'select', 'submit', 'unload'
    dom_event_type = 'HTMLEvents'
    dom_event_init = "initEvent(\"#{event}\", true, true)"
    when 'keydown', 'keypress', 'keyup'
    dom_event_type = 'KeyEvents'
    # Firefox has a proprietary initializer for keydown/keypress/keyup.
    # Args are as follows:
    #   'type', bubbles, cancelable, windowObject, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode
    dom_event_init = "initKeyEvent(\"#{event}\", true, true, #{@container.window_var}, false, false, false, false, 0, 0)"
    when 'click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover',
                  'mouseup'
    dom_event_type = 'MouseEvents'
    # Args are as follows:
    #   'type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget
    if(@container.window_var == nil || @container.window_var == '')
      dom_event_init = "initMouseEvent(\"#{event}\", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null)"
    else
      dom_event_init = "initMouseEvent(\"#{event}\", true, true, #{@container.window_var}, 1, 0, 0, 0, 0, false, false, false, false, 0, null)"        
    end
  else
    dom_event_type = 'HTMLEvents'
    dom_event_init = "initEvents(\"#{event}\", true, true)"
  end

  if(element_type == "HTMLSelectElement")
    dom_event_type = 'HTMLEvents'
    dom_event_init = "initEvent(\"#{event}\", true, true)"
  end


  jssh_command  = "var event = #{@container.document_var}.createEvent(\"#{dom_event_type}\"); "
  jssh_command << "event.#{dom_event_init}; "
  jssh_command << "#{element_object}.dispatchEvent(event);"

  #puts "JSSH COMMAND:\n#{jssh_command}\n"

  jssh_socket.send("#{jssh_command}\n", 0)
  read_socket() if wait
  wait() if wait

  @@current_level = 0
end

#inspectObject



691
692
693
# File 'lib/firewatir/element.rb', line 691

def inspect
  '#<%s:0x%x located=%s how=%s what=%s>' % [self.class, hash*2, !!@o, @how.inspect, @what.inspect]
end

#textObject Also known as: innerText

Description:

Returns the text of the element.

Output:

Text of the element.


998
999
1000
1001
1002
1003
1004
# File 'lib/firewatir/element.rb', line 998

def text()
  assert_exists
  element = (element_type == "HTMLFrameElement") ? "body" : element_object
  return_value = js_eval("#{element}.textContent.replace(/\\xA0/g, ' ').replace(/\\s+/g, ' ')").strip
  @@current_level = 0
  return return_value
end

#to_s(attributes = nil) ⇒ Object

Description:

Display basic details about the object. Sample output for a button is shown.
Raises UnknownObjectException if the object is not found.
   name      b4
   type      button
   id         b5
   value      Disabled Button
   disabled   true

Output:

Array with value of properties shown above.


1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/firewatir/element.rb', line 1052

def to_s(attributes=nil)
  #puts "here in to_s"
  #puts caller(0)
  assert_exists
  if(element_type == "HTMLTableCellElement")
    return text()
  else
    result = string_creator(attributes).join("\n")
    @@current_level = 0
    return result
  end
end

#visible?Boolean

Description:

Checks element for display: none or visibility: hidden, these are
the most common methods to hide an html element

Returns:

  • (Boolean)


947
948
949
950
951
# File 'lib/firewatir/element.rb', line 947

def visible?
  assert_exists
  val = js_eval "var val = 'true'; var str = ''; var obj = #{element_object}; while (obj != null) { try { str = #{@container.document_var}.defaultView.getComputedStyle(obj,null).visibility; if (str=='hidden') { val = 'false'; break; } str = #{@container.document_var}.defaultView.getComputedStyle(obj,null).display; if (str=='none') { val = 'false'; break; } } catch(err) {} obj = obj.parentNode; } val;"
  return (val == 'false')? false: true
end

#waitObject

Description:

Wait for the browser to get loaded, after the event is being fired.


1118
1119
1120
1121
1122
1123
1124
# File 'lib/firewatir/element.rb', line 1118

def wait
  #ff = FireWatir::Firefox.new
  #ff.wait()
  #puts @container
  @container.wait()
  @@current_level = 0
end