WebElement.pm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. package Selenium::Remote::WebElement;
  2. # ABSTRACT: Representation of an HTML Element used by Selenium Remote Driver
  3. use strict;
  4. use warnings;
  5. use Moo;
  6. use Carp qw(carp croak);
  7. =head1 DESCRIPTION
  8. Selenium Webdriver represents all the HTML elements as WebElements.
  9. This module provides a mechanism to represent them as objects &
  10. perform various actions on the related elements. This module should
  11. not be instantiated directly by the end user. Selenium::Remote::Driver
  12. instantiates this module when required. Typically, the find_element
  13. method in Selenium::Remote::Driver returns this object on which
  14. various element related operations can be carried out.
  15. What is probably most useful on this page is the list of methods below
  16. that you can perform on an element once you've found one and S::R::D
  17. has made an instance of this for you.
  18. =head1 CONSTRUCTOR
  19. =head2 new
  20. =over 4
  21. =item B<id>
  22. Required: Pass in a string representing the ID of the object. The
  23. string should be obtained from the response object of making one of
  24. the C<find_element> calls from L<Selenium::Remote::Driver>.
  25. The attribute is also set up to handle spec compliant element response
  26. objects via its `coerce` such that any of the following will work and
  27. are all equivalent:
  28. my $old_elem = Selenium::Remote::WebElement->new(
  29. id => 1,
  30. driver => $driver
  31. );
  32. my $new_remote_elem = Selenium::Remote::WebElement->new(
  33. id => { ELEMENT => 1 },
  34. driver => $driver
  35. );
  36. my $new_spec_elem = Selenium::Remote::WebElement->new(
  37. id => { 'element-6066-11e4-a52e-4f735466cecf' => 1 },
  38. driver => $driver
  39. );
  40. and then after instantiation, all three would give the following for
  41. `id`:
  42. print $elem->id; # prints 1
  43. =item B<driver>
  44. Required: Pass in a Selenium::Remote::Driver instance or one of its
  45. subclasses. The WebElement needs the appropriate Driver session to
  46. execute its commands properly.
  47. =back
  48. For typical usage of S::R::D and this module, none of this
  49. matters and it should Just Work without you having to worry about it
  50. at all. For further reading, the L<W3C
  51. spec|https://www.w3.org/TR/webdriver/#elements> strictly dictates the
  52. exact behavior.
  53. =cut
  54. has 'id' => (
  55. is => 'ro',
  56. required => 1,
  57. coerce => sub {
  58. my ($value) = @_;
  59. if (ref($value) eq 'HASH') {
  60. if (exists $value->{ELEMENT}) {
  61. # The JSONWireProtocol web element object looks like
  62. #
  63. # { "ELEMENT": $INTEGER_ID }
  64. return $value->{ELEMENT};
  65. }
  66. elsif (exists $value->{'element-6066-11e4-a52e-4f735466cecf'}) {
  67. # but the WebDriver spec web element uses a magic
  68. # string. See the spec for more information:
  69. #
  70. # https://www.w3.org/TR/webdriver/#elements
  71. return $value->{'element-6066-11e4-a52e-4f735466cecf'};
  72. }
  73. else {
  74. croak 'When passing in an object to the WebElement id attribute, it must have at least one of the ELEMENT or element-6066-11e4-a52e-4f735466cecf keys.';
  75. }
  76. }
  77. else {
  78. return $value;
  79. }
  80. }
  81. );
  82. has 'driver' => (
  83. is => 'ro',
  84. required => 1,
  85. handles => [qw(_execute_command)],
  86. );
  87. =head1 FUNCTIONS
  88. =head2 child(selector, method)
  89. =head2 children(selector, method)
  90. Alias to Selenium::Remote::Driver::find_child_element and find_child_elements, respectively.
  91. =cut
  92. sub child {
  93. return $_[0]->{driver}->find_child_element(@_);
  94. }
  95. sub children {
  96. return $_[0]->{driver}->find_child_elements(@_);
  97. }
  98. =head2 click
  99. Description:
  100. Click the element.
  101. Usage:
  102. $elem->click();
  103. =cut
  104. sub click {
  105. my ($self) = @_;
  106. my $res = { 'command' => 'clickElement', 'id' => $self->id };
  107. return $self->_execute_command($res);
  108. }
  109. =head2 submit
  110. Description:
  111. Submit a FORM element. The submit command may also be applied to any element
  112. that is a descendant of a FORM element.
  113. Compatibility:
  114. On webdriver3 enabled servers, this uses a JS shim, which WILL NOT submit correctly unless your element is an <input>.
  115. Try clicking it if possible instead.
  116. Usage:
  117. $elem->submit();
  118. =cut
  119. sub submit {
  120. my ($self) = @_;
  121. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  122. if ($self->get_tag_name() ne 'form') {
  123. return $self->driver->execute_script("return arguments[0].form.submit();",{'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}} );
  124. } else {
  125. return $self->driver->execute_script("return arguments[0].submit();",{'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}} );
  126. }
  127. }
  128. my $res = { 'command' => 'submitElement', 'id' => $self->id };
  129. return $self->_execute_command($res);
  130. }
  131. =head2 send_keys
  132. Description:
  133. Send a sequence of key strokes to an element. If you want to send specific
  134. Keyboard events, then use the WDKeys module along with theis method. See e.g.
  135. for reference
  136. Input: 1
  137. Required:
  138. {ARRAY | STRING} - Array of strings or a string.
  139. Usage:
  140. $elem->send_keys('abcd', 'efg');
  141. $elem->send_keys('hijk');
  142. or
  143. # include the WDKeys module
  144. use Selenium::Remote::WDKeys;
  145. .
  146. .
  147. $elem->send_keys(KEYS->{'space'}, KEYS->{'enter'});
  148. =cut
  149. sub send_keys {
  150. my ( $self, @strings ) = @_;
  151. croak "no keys to send" unless scalar @strings >= 1;
  152. my $res = { 'command' => 'sendKeysToElement', 'id' => $self->id };
  153. # We need to send an array of single characters to be WebDriver
  154. # spec compatible. That is, for @strings = ('hel', 'lo'), the
  155. # corresponding value must be ('h', 'e', 'l', 'l', 'o' ). This
  156. # format conforms with the Spec AND works with the Selenium
  157. # standalone server.
  158. my $strings = join('', map { $_."" } @strings);
  159. my $params = {
  160. 'value' => [ split('', $strings) ],
  161. text => $strings,
  162. };
  163. return $self->_execute_command( $res, $params );
  164. }
  165. =head2 is_selected
  166. Description:
  167. Determine if an OPTION element, or an INPUT element of type checkbox or
  168. radiobutton is currently selected.
  169. Output:
  170. BOOLEAN - whether the element is selected
  171. Usage:
  172. $elem->is_selected();
  173. =cut
  174. sub is_selected {
  175. my ($self) = @_;
  176. return $self->get_property('checked') if $self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge});
  177. my $res = { 'command' => 'isElementSelected', 'id' => $self->id };
  178. return $self->_execute_command($res);
  179. }
  180. =head2 set_selected
  181. Description:
  182. Select an OPTION element, or an INPUT element of type checkbox or radiobutton.
  183. Forces selected=1 on the element..
  184. Usage:
  185. $elem->set_selected();
  186. =cut
  187. sub set_selected {
  188. my ($self) = @_;
  189. if ($self->driver->{is_wd3}) {
  190. return if $self->is_selected();
  191. return $self->click();
  192. }
  193. my $res = { 'command' => 'setElementSelected', 'id' => $self->id };
  194. return $self->_execute_command($res);
  195. }
  196. =head2 toggle
  197. Description:
  198. Toggle whether an OPTION element, or an INPUT element of type checkbox or
  199. radiobutton is currently selected.
  200. Output:
  201. BOOLEAN - Whether the element is selected after toggling its state.
  202. Usage:
  203. $elem->toggle();
  204. =cut
  205. sub toggle {
  206. my ($self) = @_;
  207. if ($self->driver->{is_wd3}) {
  208. return $self->click() unless $self->is_selected();
  209. return $self->driver->execute_script(qq/ if (arguments[0].checked) { arguments[0].checked = 0 }; return arguments[0].checked; /, {'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}});
  210. }
  211. my $res = { 'command' => 'toggleElement', 'id' => $self->id };
  212. return $self->_execute_command($res);
  213. }
  214. =head2 is_enabled
  215. Description:
  216. Determine if an element is currently enabled.
  217. Output:
  218. BOOLEAN - Whether the element is enabled.
  219. Usage:
  220. $elem->is_enabled();
  221. =cut
  222. sub is_enabled {
  223. my ($self) = @_;
  224. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  225. return 1 if $self->get_tag_name() ne 'input';
  226. return $self->get_property('disabled') ? 0 : 1;
  227. }
  228. my $res = { 'command' => 'isElementEnabled', 'id' => $self->id };
  229. return $self->_execute_command($res);
  230. }
  231. =head2 get_element_location
  232. Description:
  233. Determine an element's location on the page. The point (0, 0) refers to the
  234. upper-left corner of the page.
  235. Compatibility:
  236. On WebDriver 3 enabled servers, this is an alias for get_element_rect().
  237. Output:
  238. HASH - The X and Y coordinates for the element on the page.
  239. Usage:
  240. $elem->get_element_location();
  241. This method is DEPRECATED on webdriver3 enabled servers.
  242. =cut
  243. sub get_element_location {
  244. my ($self) = @_;
  245. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  246. my $data = $self->get_element_rect();
  247. delete $data->{height};
  248. delete $data->{width};
  249. return $data;
  250. }
  251. my $res = { 'command' => 'getElementLocation', 'id' => $self->id };
  252. return $self->_execute_command($res);
  253. }
  254. =head2 get_size
  255. Description:
  256. Determine an element's size in pixels. The size will be returned with width
  257. and height properties.
  258. Compatibility:
  259. On WebDriver 3 enabled servers, this is an alias for get_element_rect().
  260. Output:
  261. HASH - The width and height of the element, in pixels.
  262. Usage:
  263. $elem->get_size();
  264. This method is DEPRECATED on webdriver3 enabled servers.
  265. =cut
  266. sub get_size {
  267. my ($self) = @_;
  268. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  269. my $data = $self->get_element_rect();
  270. delete $data->{x};
  271. delete $data->{y};
  272. return $data;
  273. }
  274. my $res = { 'command' => 'getElementSize', 'id' => $self->id };
  275. return $self->_execute_command($res);
  276. }
  277. =head2 get_element_rect
  278. Get the element's size AND location in a hash.
  279. Example Output:
  280. { x => 0, y => 0, height => 10, width => 10 }
  281. =cut
  282. sub get_element_rect {
  283. my ($self) = @_;
  284. my $res = { 'command' => 'getElementRect', 'id' => $self->id };
  285. return $self->_execute_command($res);
  286. }
  287. =head2 get_element_location_in_view
  288. Description:
  289. Determine an element's location on the screen once it has been scrolled
  290. into view.
  291. Note: This is considered an internal command and should only be used to
  292. determine an element's location for correctly generating native events.
  293. Compatibility:
  294. On Webdriver3 servers, we have to implement this with a JS shim.
  295. This means in some contexts, you won't get any position returned, as the element isn't considered an element internally.
  296. You may have to go up the element stack to find the element that actually has the bounding box.
  297. Output:
  298. {x:number, y:number} The X and Y coordinates for the element on the page.
  299. Usage:
  300. $elem->get_element_location_in_view();
  301. =cut
  302. sub get_element_location_in_view {
  303. my ($self) = @_;
  304. #XXX chrome is dopey here
  305. return $self->driver->execute_script(qq{
  306. if (typeof(arguments[0]) !== 'undefined' && arguments[0].nodeType === Node.ELEMENT_NODE) {
  307. arguments[0].scrollIntoView();
  308. var pos = arguments[0].getBoundingClientRect();
  309. return {y:pos.top,x:pos.left};
  310. }
  311. return {};
  312. }, {'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}} ) if $self->driver->{is_wd3} && grep { $self->driver->browser_name eq $_ } ('firefox','internet explorer');
  313. my $res = { 'command' => 'getElementLocationInView', 'id' => $self->id };
  314. return $self->_execute_command($res);
  315. }
  316. =head2 get_tag_name
  317. Description:
  318. Query for an element's tag name.
  319. Output:
  320. STRING - The element's tag name, as a lowercase string.
  321. Usage:
  322. $elem->get_tag_name();
  323. =cut
  324. sub get_tag_name {
  325. my ($self) = @_;
  326. my $res = { 'command' => 'getElementTagName', 'id' => $self->id };
  327. return $self->_execute_command($res);
  328. }
  329. =head2 clear
  330. Description:
  331. Clear a TEXTAREA or text INPUT element's value.
  332. Usage:
  333. $elem->clear();
  334. =cut
  335. sub clear {
  336. my ($self) = @_;
  337. my $res = { 'command' => 'clearElement', 'id' => $self->id };
  338. return $self->_execute_command($res);
  339. }
  340. =head2 get_attribute
  341. Description:
  342. Get the value of an element's attribute.
  343. Compatibility:
  344. In older webDriver, this actually got the value of an element's property.
  345. If you want to get the initial condition (e.g. the values in the tag hardcoded in HTML), pass 1 as the second argument.
  346. Or, set $driver->{emulate_jsonwire} = 0 to not have to pass the extra arg.
  347. This can only done on WebDriver 3 enabled servers.
  348. Input: 2
  349. Required:
  350. STRING - name of the attribute of the element
  351. Optional:
  352. BOOLEAN - "I really mean that I want the initial condition, quit being so compatible!!!"
  353. Output:
  354. {STRING | NULL} The value of the attribute, or null if it is not set on the element.
  355. Usage:
  356. $elem->get_attribute('name',1);
  357. =cut
  358. sub get_attribute {
  359. my ( $self, $attr_name, $no_i_really_mean_it ) = @_;
  360. if ( not defined $attr_name ) {
  361. croak 'Attribute name not provided';
  362. }
  363. #Handle global JSONWire emulation flag
  364. $no_i_really_mean_it = 1 unless $self->{driver}->{emulate_jsonwire};
  365. return $self->get_property($attr_name) if $self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge}) && !$no_i_really_mean_it;
  366. my $res = {
  367. 'command' => 'getElementAttribute',
  368. 'id' => $self->id,
  369. 'name' => $attr_name,
  370. };
  371. return $self->_execute_command($res);
  372. }
  373. =head2 get_property
  374. Gets the C<Current Value> of an element's attribute.
  375. Takes a named property as an argument.
  376. Only available on WebDriver 3 enabled servers.
  377. =cut
  378. sub get_property {
  379. my ($self,$prop) = @_;
  380. return $self->get_attribute($prop) if $self->driver->{is_wd3} && (grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge});
  381. my $res = { 'command' => 'getElementProperty', id => $self->id, name => $prop };
  382. return $self->_execute_command($res);
  383. }
  384. =head2 get_value
  385. Description:
  386. Query for the value of an element, as determined by its value attribute.
  387. Output:
  388. {STRING | NULL} The element's value, or null if it doesn't have a value attribute.
  389. Usage:
  390. $elem->get_value();
  391. =cut
  392. sub get_value {
  393. my ($self) = @_;
  394. return $self->get_attribute('value');
  395. }
  396. =head2 is_displayed
  397. Description:
  398. Determine if an element is currently displayed.
  399. Note: This does *not* tell you an element's 'visibility' property; as it still takes up space in the DOM and is therefore considered 'displayed'.
  400. WC3 Compatibility:
  401. On JSONWire this method really only checked to see whether the element's style was display:none, or whether it was a hidden input.
  402. This is because "displayedness" was pretty loosely defined until fairly late on into the process, and much grief resulted.
  403. In WC3 webdriver, it additionally does a viewport check, to account for the firmer definition of "displayedness":
  404. https://w3c.github.io/webdriver/#element-displayedness
  405. Output:
  406. BOOLEAN - Whether the element is displayed.
  407. Usage:
  408. $elem->is_displayed();
  409. =cut
  410. sub is_displayed {
  411. my ($self) = @_;
  412. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  413. return 0 if $self->get_tag_name() eq 'input' && $self->get_property('type') eq 'hidden'; #hidden type inputs
  414. return 0 unless $self->_is_in_viewport();
  415. return int($self->get_css_attribute('display') ne 'none');
  416. }
  417. my $res = { 'command' => 'isElementDisplayed', 'id' => $self->id };
  418. return $self->_execute_command($res);
  419. }
  420. sub _is_in_viewport {
  421. my ($self) = @_;
  422. return $self->driver->execute_script(qq{
  423. var rect = arguments[0].getBoundingClientRect();
  424. return (
  425. rect.top >= 0 &&
  426. rect.left >= 0 &&
  427. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
  428. rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  429. );
  430. },{'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}});
  431. }
  432. =head2 is_hidden
  433. Description:
  434. Determine if an element is currently hidden.
  435. Output:
  436. BOOLEAN - Whether the element is hidden.
  437. Usage:
  438. $elem->is_hidden();
  439. =cut
  440. sub is_hidden {
  441. my ($self) = @_;
  442. return ! $self->is_displayed();
  443. }
  444. =head2 drag
  445. Alias for Selenium::ActionChains::drag_and_drop().
  446. Provide element you wish to drag to as argument.
  447. my $target = $driver->find_element('receptacle','id');
  448. my $subject = $driver->find_element('thingy','id');
  449. $subject->drag($target);
  450. =cut
  451. sub drag {
  452. my ($self,$target) = @_;
  453. require Selenium::ActionChains;
  454. my $chain = Selenium::ActionChains->new( driver => $self->driver );
  455. return $chain->drag_and_drop($self,$target)->perform();
  456. }
  457. =head2 get_text
  458. Description:
  459. Get the innerText of the element.
  460. Output:
  461. STRING - innerText of an element
  462. Usage:
  463. $elem->get_text();
  464. =cut
  465. sub get_text {
  466. my ($self) = @_;
  467. my $res = { 'command' => 'getElementText', 'id' => $self->id };
  468. return $self->_execute_command($res);
  469. }
  470. =head2 get_css_attribute
  471. Description:
  472. Query the value of an element's computed CSS property. The CSS property to
  473. query should be specified using the CSS property name, not the JavaScript
  474. property name (e.g. background-color instead of backgroundColor).
  475. Input: 1
  476. Required:
  477. STRING - name of the css-attribute
  478. Output:
  479. STRING - Value of the css attribute
  480. Usage:
  481. $elem->get_css_attribute('background-color');
  482. =cut
  483. sub get_css_attribute {
  484. my ( $self, $attr_name ) = @_;
  485. if ( not defined $attr_name ) {
  486. croak 'CSS attribute name not provided';
  487. }
  488. my $res = {
  489. 'command' => 'getElementValueOfCssProperty',
  490. 'id' => $self->id,
  491. 'property_name' => $attr_name,
  492. };
  493. return $self->_execute_command($res);
  494. }
  495. =head2 describe
  496. Description:
  497. Describe the identified element
  498. Usage:
  499. $elem->describe();
  500. Note: DEPRECATED as of 2.42.2 -- use get_text, get_value, is_displayed, or
  501. whatever appropriate WebElement function you need instead
  502. Entirely unsupported on WebDriver 3 enabled servers.
  503. =cut
  504. sub describe {
  505. my ($self) = @_;
  506. my $res = { 'command' => 'describeElement', 'id' => $self->id };
  507. return $self->_execute_command($res);
  508. }
  509. =head2 screenshot
  510. Description:
  511. Get a screenshot of the visible region that is a subset of the element's bounding box as a base64 encoded image.
  512. Compatibility:
  513. Only available on Webdriver3 enabled selenium servers.
  514. Input (optional):
  515. $scroll_into_view - BOOLEAN default true. If false, will not scroll the element into the viewport first.
  516. Failing to do so may result in an image being cropped partially or entirely.
  517. Output:
  518. STRING - base64 encoded image
  519. Usage:
  520. print $element->screenshot();
  521. To conveniently write the screenshot to a file, see L</capture_screenshot>.
  522. =cut
  523. sub screenshot {
  524. my ($self, $scroll) = @_;
  525. $scroll //= 1;
  526. my $res = { 'command' => 'elementScreenshot', id => $self->id };
  527. my $input = {scroll => int($scroll) };
  528. return $self->_execute_command($res, $input);
  529. }
  530. =head2 capture_screenshot
  531. Description:
  532. Capture a screenshot of said element and save as a PNG to provided file name.
  533. Compatibility:
  534. Only available on Webdriver3 enabled selenium servers.
  535. Input (optional):
  536. $scroll_into_view - BOOLEAN default true. If false, will not scroll the element into the viewport first.
  537. Failing to do so may result in an image being cropped partially or entirely.
  538. Output:
  539. TRUE - (Screenshot is written to file)
  540. Usage:
  541. $element->capture_screenshot($filename);
  542. =cut
  543. sub capture_screenshot {
  544. my ( $self, $filename, $scroll ) = @_;
  545. croak '$filename is required' unless $filename;
  546. open( my $fh, '>', $filename );
  547. binmode $fh;
  548. print $fh MIME::Base64::decode_base64( $self->screenshot($scroll) );
  549. CORE::close $fh;
  550. return 1;
  551. }
  552. 1;