Driver.pm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. package Selenium::Remote::Driver;
  2. use strict;
  3. use warnings;
  4. use Data::Dumper;
  5. use Carp qw(croak);
  6. use Selenium::Remote::RemoteConnection;
  7. use Selenium::Remote::Commands;
  8. use Selenium::Remote::WebElement;
  9. use constant FINDERS => {
  10. class => 'class name',
  11. class_name => 'class name',
  12. css => 'css selector',
  13. id => 'id',
  14. link => 'link text',
  15. link_text => 'link text',
  16. name => 'name',
  17. partial_link_text => 'partial link text',
  18. tag_name => 'tag name',
  19. xpath => 'xpath',
  20. };
  21. our $VERSION = "0.10";
  22. =head1 NAME
  23. Selenium::Remote::Driver - Perl Client for Selenium Remote Driver
  24. =cut
  25. =head1 SYNOPSIS
  26. use Selenium::Remote::Driver;
  27. my $driver = new Selenium::Remote::Driver;
  28. $driver->get('http://www.google.com');
  29. print $driver->get_title();
  30. $driver->quit();
  31. =cut
  32. =head1 DESCRIPTION
  33. Selenium is a test tool that allows you to write
  34. automated web application UI tests in any programming language against
  35. any HTTP website using any mainstream JavaScript-enabled browser. This module is
  36. an implementation of the client for the Remote driver that Selenium provides.
  37. You can find bindings for other languages at this location:
  38. L<http://code.google.com/p/selenium/>
  39. This module sends commands directly to the Server using HTTP. Using this module
  40. together with the Selenium Server, you can automatically control any supported
  41. browser. To use this module, you need to have already downloaded and started
  42. the Selenium Server (Selenium Server is a Java application).
  43. =cut
  44. =head1 USAGE (read this first)
  45. =head2 Remote Driver Response
  46. Selenium::Remote::Driver uses the L<JsonWireProtocol|http://code.google.com/p/selenium/wiki/JsonWireProtocol> to communicate with the
  47. Selenium Server. If an error occurs while executing the command then the server
  48. sends back an HTTP error code with a JSON encoded reponse that indicates the
  49. precise L<Response Error Code|http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes>. The module will then croak with the error message
  50. associated with this code. If no error occurred, then the subroutine called will
  51. return the value sent back from the server (if a return value was sent).
  52. =back
  53. So a rule of thumb while invoking methods on the driver is if the method did not
  54. croak when called, then you can safely assume the command was successful even if
  55. nothing was returned by the method.
  56. =head2 WebElement
  57. Selenium Webdriver represents all the HTML elements as WebElement, which is
  58. in turn represented by Selenium::Remote::WebElement module. So any method that
  59. deals with WebElements will return and/or expect WebElement object. The POD for
  60. that module describes all the methods that perform various actions on the
  61. WebElements like click, submit etc.
  62. To interact with any WebElement you have to first "find" it, read the POD for
  63. find_element or find_elements for further info. Once you find the required element
  64. then you can perform various actions. If you don't call find_* method first, all
  65. your further actions will fail for that element. Finally, just remember that you
  66. don't have to instantiate WebElement objects at all - they will be automatically
  67. created when you use the find_* methods.
  68. =cut
  69. =head1 FUNCTIONS
  70. =cut
  71. =head2 new
  72. Description:
  73. Constructor for Driver. It'll instantiate the object if it can communicate
  74. with the Selenium RC server.
  75. Input: 7 (all optional)
  76. desired_capabilities - HASH - Following options are accepted:
  77. Optional:
  78. 'remote_server_addr' - <string> - IP or FQDN of the RC server machine
  79. 'browser_name' - <string> - desired browser string:
  80. {iphone|firefox|internet explorer|htmlunit|iphone|chrome}
  81. 'version' - <string> - desired browser version number
  82. 'platform' - <string> - desired platform:
  83. {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}
  84. 'javascript' - <boolean> - whether javascript should be supported
  85. 'auto_close' - <boolean> - whether driver should end session on remote
  86. server on close.
  87. 'extra_capabilities' - HASH of extra capabilities
  88. If no values are provided, then these defaults will be assumed:
  89. 'remote_server_addr' => 'localhost'
  90. 'port' => '4444'
  91. 'browser_name' => 'firefox'
  92. 'version' => ''
  93. 'platform' => 'ANY'
  94. 'javascript' => 1
  95. 'auto_close' => 1
  96. Output:
  97. Remote Driver object
  98. Usage:
  99. my $driver = new Selenium::Remote::Driver;
  100. or
  101. my $driver = new Selenium::Remote::Driver('browser_name' => 'firefox',
  102. 'platform' => 'MAC');
  103. or
  104. my $driver = new Selenium::Remote::Driver('remote_server_addr' => '10.10.1.1',
  105. 'port' => '2222',
  106. auto_close => 0
  107. );
  108. or
  109. my $driver = new Selenium::Remote::Driver('browser_name' => 'chrome',
  110. 'platform' => 'VISTA',
  111. 'extra_capabilities' => {'chrome.switches' => ["--user-data-dir=$ENV{LOCALAPPDATA}\\Google\\Chrome\\User Data"],},
  112. );
  113. =cut
  114. sub new {
  115. my ( $class, %args ) = @_;
  116. my $ress = new Selenium::Remote::Commands;
  117. # Set the defaults if user doesn't send any
  118. my $self = {
  119. remote_server_addr => delete $args{remote_server_addr} || 'localhost',
  120. browser_name => delete $args{browser_name} || 'firefox',
  121. platform => delete $args{platform} || 'ANY',
  122. port => delete $args{port} || '4444',
  123. version => delete $args{version} || '',
  124. session_id => undef,
  125. remote_conn => undef,
  126. commands => $ress,
  127. auto_close => 1, # by default we will close remote session on DESTROY
  128. pid => $$,
  129. };
  130. bless $self, $class or die "Can't bless $class: $!";
  131. if ( defined $args{javascript} ) {
  132. if ( $args{javascript} ) {
  133. $self->{javascript} = JSON::true;
  134. }
  135. else {
  136. $self->{javascript} = JSON::false;
  137. }
  138. }
  139. else {
  140. $self->{javascript} = JSON::true;
  141. }
  142. # Connect to remote server & establish a new session
  143. $self->{remote_conn} =
  144. new Selenium::Remote::RemoteConnection( $self->{remote_server_addr},
  145. $self->{port} );
  146. $self->new_session(delete $args{extra_capabilities});
  147. if ( !( defined $self->{session_id} ) ) {
  148. croak "Could not establish a session with the remote server\n";
  149. }
  150. return $self;
  151. }
  152. sub DESTROY {
  153. my ($self) = @_;
  154. return if $$ != $self->{pid};
  155. $self->quit() if ($self->{auto_close} && defined $self->{session_id});
  156. }
  157. # This is an internal method used the Driver & is not supposed to be used by
  158. # end user. This method is used by Driver to set up all the parameters
  159. # (url & JSON), send commands & receive processed response from the server.
  160. sub _execute_command {
  161. my ( $self, $res, $params ) = @_;
  162. $res->{'session_id'} = $self->{'session_id'};
  163. my $resource = $self->{commands}->get_params($res);
  164. if ($resource) {
  165. my $resp = $self->{remote_conn}
  166. ->request( $resource->{'method'}, $resource->{'url'}, $params );
  167. if(ref($resp) eq 'HASH') {
  168. if($resp->{cmd_status} eq 'OK') {
  169. return $resp->{cmd_return};
  170. } else {
  171. my $msg = "Error while executing command";
  172. if($resp->{cmd_error}) {
  173. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  174. } else {
  175. if(ref($resp->{cmd_return}) eq 'HASH') {
  176. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  177. if $resp->{cmd_return}->{error}->{msg};
  178. } else {
  179. $msg .= ": $resp->{cmd_return}";
  180. }
  181. }
  182. croak $msg;
  183. }
  184. }
  185. return $resp;
  186. }
  187. else {
  188. croak "Couldn't retrieve command settings properly\n";
  189. }
  190. }
  191. # A method that is used by the Driver itself. It'll be called to set the
  192. # desired capabilities on the server.
  193. sub new_session {
  194. my ($self, $extra_capabilities) = @_;
  195. $extra_capabilities ||= {};
  196. my $args = {
  197. 'desiredCapabilities' => {
  198. 'browserName' => $self->{browser_name},
  199. 'platform' => $self->{platform},
  200. 'javascriptEnabled' => $self->{javascript},
  201. 'version' => $self->{version},
  202. %$extra_capabilities,
  203. },
  204. };
  205. my $resp =
  206. $self->{remote_conn}
  207. ->request( $self->{commands}->{'newSession'}->{'method'},
  208. $self->{commands}->{'newSession'}->{'url'}, $args, );
  209. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  210. $self->{session_id} = $resp->{'sessionId'};
  211. }
  212. else {
  213. croak "Could not create new session";
  214. }
  215. }
  216. =head2 status
  217. Description:
  218. Query the server's current status. All server implementations
  219. should return two basic objects describing the server's current
  220. platform and when the server was built.
  221. Output:
  222. Hash ref
  223. Usage:
  224. print Dumper $driver->status;
  225. =cut
  226. sub status {
  227. my ($self) = @_;
  228. my $res = { 'command' => 'status' };
  229. return $self->_execute_command($res);
  230. }
  231. =head2 mouse_move_to_location
  232. Description:
  233. Move the mouse by an offset of the specificed element. If no
  234. element is specified, the move is relative to the current mouse
  235. cursor. If an element is provided but no offset, the mouse will be
  236. moved to the center of the element. If the element is not visible,
  237. it will be scrolled into view.
  238. Output:
  239. STRING -
  240. Usage:
  241. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  242. # xoffset - X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  243. # yoffset - Y offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
  244. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  245. =cut
  246. sub mouse_move_to_location {
  247. my ($self, %params) = @_;
  248. $params{element} = $params{element}{id} if exists $params{element};
  249. my $res = { 'command' => 'mouseMoveToLocation' };
  250. return $self->_execute_command($res, \%params);
  251. }
  252. =head2 get_capabilities
  253. Description:
  254. Retrieve the capabilities of the specified session.
  255. Output:
  256. HASH of all the capabilities.
  257. Usage:
  258. my $capab = $driver->get_capabilities();
  259. print Dumper($capab);
  260. =cut
  261. sub get_capabilities {
  262. my $self = shift;
  263. my $res = {'command' => 'getCapabilities'};
  264. return $self->_execute_command($res);
  265. }
  266. =head2 set_implicit_wait_timeout
  267. Description:
  268. Set the amount of time the driver should wait when searching for elements.
  269. When searching for a single element, the driver will poll the page until
  270. an element is found or the timeout expires, whichever occurs first.
  271. When searching for multiple elements, the driver should poll the page until
  272. at least one element is found or the timeout expires, at which point it
  273. will return an empty list. If this method is never called, the driver will
  274. default to an implicit wait of 0ms.
  275. Input:
  276. Time in milliseconds.
  277. Output:
  278. Server Response Hash with no data returned back from the server.
  279. Usage:
  280. $driver->set_implicit_wait_timeout(10);
  281. =cut
  282. sub set_implicit_wait_timeout {
  283. my ($self, $ms) = @_;
  284. my $res = {'command' => 'setImplicitWaitTimeout'};
  285. my $params = {'ms' => $ms};
  286. return $self->_execute_command($res, $params);
  287. }
  288. =head2 close
  289. Description:
  290. Close the current window.
  291. Usage:
  292. $driver->close();
  293. or
  294. #close a popup window
  295. my $handles = $driver->get_window_handles;
  296. $driver->switch_to_window($handles->[1]);
  297. $driver->close();
  298. $driver->switch_to_window($handles->[0]);
  299. =cut
  300. sub close {
  301. my $self = shift;
  302. my $res = { 'command' => 'close' };
  303. $self->_execute_command($res);
  304. }
  305. =head2 quit
  306. Description:
  307. Delete the session & close open browsers.
  308. Usage:
  309. $driver->quit();
  310. =cut
  311. sub quit {
  312. my $self = shift;
  313. my $res = { 'command' => 'quit' };
  314. $self->_execute_command($res);
  315. $self->{session_id} = undef;
  316. }
  317. =head2 get_current_window_handle
  318. Description:
  319. Retrieve the current window handle.
  320. Output:
  321. STRING - the window handle
  322. Usage:
  323. print $driver->get_current_window_handle();
  324. =cut
  325. sub get_current_window_handle {
  326. my $self = shift;
  327. my $res = { 'command' => 'getCurrentWindowHandle' };
  328. return $self->_execute_command($res);
  329. }
  330. =head2 get_window_handles
  331. Description:
  332. Retrieve the list of window handles used in the session.
  333. Output:
  334. ARRAY of STRING - list of the window handles
  335. Usage:
  336. print Dumper $driver->get_window_handles;
  337. or
  338. # get popup, close, then back
  339. my $handles = $driver->get_window_handles;
  340. $driver->switch_to_window($handles->[1]);
  341. $driver->close;
  342. $driver->switch_to_window($handles->[0]);
  343. =cut
  344. sub get_window_handles {
  345. my $self = shift;
  346. my $res = { 'command' => 'getWindowHandles' };
  347. return $self->_execute_command($res);
  348. }
  349. =head2 get_current_url
  350. Description:
  351. Retrieve the url of the current page
  352. Output:
  353. STRING - url
  354. Usage:
  355. print $driver->get_current_url();
  356. =cut
  357. sub get_current_url {
  358. my $self = shift;
  359. my $res = { 'command' => 'getCurrentUrl' };
  360. return $self->_execute_command($res);
  361. }
  362. =head2 navigate
  363. Description:
  364. Navigate to a given url. This is same as get() method.
  365. Input:
  366. STRING - url
  367. Usage:
  368. $driver->navigate('http://www.google.com');
  369. =cut
  370. sub navigate {
  371. my ( $self, $url ) = @_;
  372. $self->get($url);
  373. }
  374. =head2 get
  375. Description:
  376. Navigate to a given url
  377. Input:
  378. STRING - url
  379. Usage:
  380. $driver->get('http://www.google.com');
  381. =cut
  382. sub get {
  383. my ( $self, $url ) = @_;
  384. my $res = { 'command' => 'get' };
  385. my $params = { 'url' => $url };
  386. return $self->_execute_command( $res, $params );
  387. }
  388. =head2 get_title
  389. Description:
  390. Get the current page title
  391. Output:
  392. STRING - Page title
  393. Usage:
  394. print $driver->get_title();
  395. =cut
  396. sub get_title {
  397. my $self = shift;
  398. my $res = { 'command' => 'getTitle' };
  399. return $self->_execute_command($res);
  400. }
  401. =head2 go_back
  402. Description:
  403. Equivalent to hitting the back button on the browser.
  404. Usage:
  405. $driver->go_back();
  406. =cut
  407. sub go_back {
  408. my $self = shift;
  409. my $res = { 'command' => 'goBack' };
  410. return $self->_execute_command($res);
  411. }
  412. =head2 go_forward
  413. Description:
  414. Equivalent to hitting the forward button on the browser.
  415. Usage:
  416. $driver->go_forward();
  417. =cut
  418. sub go_forward {
  419. my $self = shift;
  420. my $res = { 'command' => 'goForward' };
  421. return $self->_execute_command($res);
  422. }
  423. =head2 refresh
  424. Description:
  425. Reload the current page.
  426. Usage:
  427. $driver->refresh();
  428. =cut
  429. sub refresh {
  430. my $self = shift;
  431. my $res = { 'command' => 'goForward' };
  432. return $self->_execute_command($res);
  433. }
  434. =head2 javascript
  435. Description:
  436. returns true if javascript is enabled in the driver.
  437. Usage:
  438. if ($driver->javascript) { ...; }
  439. =cut
  440. sub javascript {
  441. my $self = shift;
  442. return $self->{javascript} == JSON::true;
  443. }
  444. =head2 execute_async_script
  445. Description:
  446. Inject a snippet of JavaScript into the page for execution in the context
  447. of the currently selected frame. The executed script is assumed to be
  448. asynchronous and must signal that is done by invoking the provided
  449. callback, which is always provided as the final argument to the function.
  450. The value to this callback will be returned to the client.
  451. Asynchronous script commands may not span page loads. If an unload event
  452. is fired while waiting for a script result, an error should be returned
  453. to the client.
  454. Input: 2 (1 optional)
  455. Required:
  456. STRING - Javascript to execute on the page
  457. Optional:
  458. ARRAY - list of arguments that need to be passed to the script.
  459. Output:
  460. {*} - Varied, depending on the type of result expected back from the script.
  461. Usage:
  462. my $script = q{
  463. var arg1 = arguments[0];
  464. var callback = arguments[arguments.length-1];
  465. var elem = window.document.findElementById(arg1);
  466. callback(elem);
  467. };
  468. my $callback = q{return arguments[0];};
  469. my $elem = $driver->execute_async_script($script,'myid',$callback);
  470. $elem->click;
  471. =cut
  472. sub execute_async_script {
  473. my ( $self, $script, @args ) = @_;
  474. if ($self->javascript) {
  475. if ( not defined $script ) {
  476. return 'No script provided';
  477. }
  478. my $res = { 'command' => 'executeAsyncScript' };
  479. # Check the args array if the elem obj is provided & replace it with
  480. # JSON representation
  481. for (my $i=0; $i<@args; $i++) {
  482. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  483. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  484. }
  485. }
  486. my $params = {'script' => $script, 'args' => \@args};
  487. my $ret = $self->_execute_command($res, $params);
  488. # replace any ELEMENTS with WebElement
  489. if (ref($ret) and (ref($ret) eq 'HASH') and exists $ret->{'ELEMENT'}) {
  490. $ret =
  491. new Selenium::Remote::WebElement(
  492. $ret->{ELEMENT}, $self);
  493. }
  494. return $ret;
  495. }
  496. else {
  497. croak 'Javascript is not enabled on remote driver instance.';
  498. }
  499. }
  500. =head2 execute_script
  501. Description:
  502. Inject a snippet of JavaScript into the page and return its result.
  503. WebElements that should be passed to the script as an argument should be
  504. specified in the arguments array as WebElement object. Likewise,
  505. any WebElements in the script result will be returned as WebElement object.
  506. Input: 2 (1 optional)
  507. Required:
  508. STRING - Javascript to execute on the page
  509. Optional:
  510. ARRAY - list of arguments that need to be passed to the script.
  511. Output:
  512. {*} - Varied, depending on the type of result expected back from the script.
  513. Usage:
  514. my $script = q{
  515. var arg1 = arguments[0];
  516. var elem = window.document.findElementById(arg1);
  517. return elem;
  518. };
  519. my $elem = $driver->execute_script($script,'myid');
  520. $elem->click;
  521. =cut
  522. sub execute_script {
  523. my ( $self, $script, @args ) = @_;
  524. if ($self->javascript) {
  525. if ( not defined $script ) {
  526. return 'No script provided';
  527. }
  528. my $res = { 'command' => 'executeScript' };
  529. # Check the args array if the elem obj is provided & replace it with
  530. # JSON representation
  531. for (my $i=0; $i<@args; $i++) {
  532. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  533. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  534. }
  535. }
  536. my $params = {'script' => $script, 'args' => [@args]};
  537. my $ret = $self->_execute_command($res, $params);
  538. # replace any ELEMENTS with WebElement
  539. if (ref($ret) and (ref($ret) eq 'HASH') and exists $ret->{'ELEMENT'}) {
  540. $ret =
  541. new Selenium::Remote::WebElement(
  542. $ret->{ELEMENT}, $self);
  543. }
  544. return $ret;
  545. }
  546. else {
  547. croak 'Javascript is not enabled on remote driver instance.';
  548. }
  549. }
  550. =head2 screenshot
  551. Description:
  552. Get a screenshot of the current page as a base64 encoded image.
  553. Output:
  554. STRING - base64 encoded image
  555. Usage:
  556. print $driver->screenshot();
  557. or
  558. require MIME::Base64;
  559. open(FH,'>','screenshot.png');
  560. binmode FH;
  561. my $png_base64 = $driver->screenshot();
  562. print FH MIME::Base64::decode_base64($png_base64);
  563. close FH;
  564. =cut
  565. sub screenshot {
  566. my ($self) = @_;
  567. my $res = { 'command' => 'screenshot' };
  568. return $self->_execute_command($res);
  569. }
  570. =head2 available_engines
  571. Description:
  572. List all available engines on the machine. To use an engine, it has to be present in this list.
  573. Output:
  574. {Array.<string>} A list of available engines
  575. Usage:
  576. print Dumper $driver->available_engines;
  577. =cut
  578. sub available_engines {
  579. my ($self) = @_;
  580. my $res = { 'command' => 'availableEngines' };
  581. return $self->_execute_command($res);
  582. }
  583. =head2 switch_to_frame
  584. Description:
  585. Change focus to another frame on the page. If the frame ID is null, the
  586. server will switch to the page's default content.
  587. Input: 1
  588. Required:
  589. {STRING | NUMBER | NULL} - ID of the frame which can be one of the three
  590. mentioned.
  591. Usage:
  592. $driver->switch_to_frame('frame_1');
  593. =cut
  594. sub switch_to_frame {
  595. my ( $self, $id ) = @_;
  596. my $json_null = JSON::null;
  597. $id = ( defined $id ) ? $id : $json_null;
  598. my $res = { 'command' => 'switchToFrame' };
  599. my $params = { 'id' => $id };
  600. return $self->_execute_command( $res, $params );
  601. }
  602. =head2 switch_to_window
  603. Description:
  604. Change focus to another window. The window to change focus to may be
  605. specified by its server assigned window handle, or by the value of its name
  606. attribute.
  607. Input: 1
  608. Required:
  609. STRING - Window handle or the Window name
  610. Usage:
  611. $driver->switch_to_window('MY Homepage');
  612. or
  613. # close a popup window and switch back
  614. my $handles = $driver->get_window_handles;
  615. $driver->switch_to_window($handles->[1]);
  616. $driver->close;
  617. $driver->switch_to_window($handles->[0]);
  618. =cut
  619. sub switch_to_window {
  620. my ( $self, $name ) = @_;
  621. if ( not defined $name ) {
  622. return 'Window name not provided';
  623. }
  624. my $res = { 'command' => 'switchToWindow' };
  625. my $params = { 'name' => $name };
  626. return $self->_execute_command( $res, $params );
  627. }
  628. =head2 get_speed
  629. Description:
  630. Get the current user input speed. The actual input speed is still browser
  631. specific and not covered by the Driver.
  632. Output:
  633. STRING - One of these: SLOW, MEDIUM, FAST
  634. Usage:
  635. print $driver->get_speed();
  636. =cut
  637. sub get_speed {
  638. my ($self) = @_;
  639. my $res = { 'command' => 'getSpeed' };
  640. return $self->_execute_command($res);
  641. }
  642. =head2 set_speed
  643. Description:
  644. Set the user input speed.
  645. Input:
  646. STRING - One of these: SLOW, MEDIUM, FAST
  647. Usage:
  648. $driver->set_speed('MEDIUM');
  649. Note: This function is a no-op in WebDriver (?). See
  650. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  651. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  652. =cut
  653. sub set_speed {
  654. my ( $self, $speed ) = @_;
  655. if ( not defined $speed ) {
  656. return 'Speed not provided.';
  657. }
  658. my $res = { 'command' => 'setSpeed' };
  659. my $params = { 'speed' => $speed };
  660. return $self->_execute_command( $res, $params );
  661. }
  662. =head2 get_all_cookies
  663. Description:
  664. Retrieve all cookies visible to the current page. Each cookie will be
  665. returned as a HASH reference with the following keys & their value types:
  666. 'name' - STRING
  667. 'value' - STRING
  668. 'path' - STRING
  669. 'domain' - STRING
  670. 'secure' - BOOLEAN
  671. Output:
  672. ARRAY of HASHES - list of all the cookie hashes
  673. Usage:
  674. print Dumper($driver->get_all_cookies());
  675. =cut
  676. sub get_all_cookies {
  677. my ($self) = @_;
  678. my $res = { 'command' => 'getAllCookies' };
  679. return $self->_execute_command($res);
  680. }
  681. =head2 add_cookie
  682. Description:
  683. Set a cookie on the domain.
  684. Input: 5 (1 optional)
  685. Required:
  686. 'name' - STRING
  687. 'value' - STRING
  688. 'path' - STRING
  689. 'domain' - STRING
  690. Optional:
  691. 'secure' - BOOLEAN - default is false.
  692. Usage:
  693. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  694. =cut
  695. sub add_cookie {
  696. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  697. if ( ( not defined $name )
  698. || ( not defined $value )
  699. || ( not defined $path )
  700. || ( not defined $domain ) )
  701. {
  702. return "Missing parameters";
  703. }
  704. my $res = { 'command' => 'addCookie' };
  705. my $json_false = JSON::false;
  706. my $json_true = JSON::true;
  707. $secure = ( defined $secure ) ? $json_true : $json_false;
  708. my $params = {
  709. 'cookie' => {
  710. 'name' => $name,
  711. 'value' => $value,
  712. 'path' => $path,
  713. 'domain' => $domain,
  714. 'secure' => $secure,
  715. }
  716. };
  717. return $self->_execute_command( $res, $params );
  718. }
  719. =head2 delete_all_cookies
  720. Description:
  721. Delete all cookies visible to the current page.
  722. Usage:
  723. $driver->delete_all_cookies();
  724. =cut
  725. sub delete_all_cookies {
  726. my ($self) = @_;
  727. my $res = { 'command' => 'deleteAllCookies' };
  728. return $self->_execute_command($res);
  729. }
  730. =head2 delete_cookie_named
  731. Description:
  732. Delete the cookie with the given name. This command will be a no-op if there
  733. is no such cookie visible to the current page.
  734. Input: 1
  735. Required:
  736. STRING - name of cookie to delete
  737. Usage:
  738. $driver->delete_cookie_named('foo');
  739. =cut
  740. sub delete_cookie_named {
  741. my ( $self, $cookie_name ) = @_;
  742. if ( not defined $cookie_name ) {
  743. return "Cookie name not provided";
  744. }
  745. my $res = { 'command' => 'deleteAllCookies', 'name' => $cookie_name };
  746. return $self->_execute_command($res);
  747. }
  748. =head2 get_page_source
  749. Description:
  750. Get the current page source.
  751. Output:
  752. STRING - The page source.
  753. Usage:
  754. print $driver->get_page_source();
  755. =cut
  756. sub get_page_source {
  757. my ($self) = @_;
  758. my $res = { 'command' => 'getPageSource' };
  759. return $self->_execute_command($res);
  760. }
  761. =head2 find_element
  762. Description:
  763. Search for an element on the page, starting from the document root. The
  764. located element will be returned as a WebElement object.
  765. Input: 2 (1 optional)
  766. Required:
  767. STRING - The search target.
  768. Optional:
  769. STRING - Locator scheme to use to search the element, available schemes:
  770. {class, class_name, css, id, link, link_text, partial_link_text,
  771. tag_name, name, xpath}
  772. Defaults to 'xpath'.
  773. Output:
  774. Selenium::Remote::WebElement - WebElement Object
  775. Usage:
  776. $driver->find_element("//input[\@name='q']");
  777. =cut
  778. sub find_element {
  779. my ( $self, $query, $method ) = @_;
  780. if ( not defined $query ) {
  781. return 'Search string to find element not provided.';
  782. }
  783. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  784. if (defined $using) {
  785. my $res = { 'command' => 'findElement' };
  786. my $params = { 'using' => $using, 'value' => $query };
  787. my $ret_data = $self->_execute_command( $res, $params );
  788. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  789. }
  790. else {
  791. croak "Bad method, expected - class, class_name, css, id, link,
  792. link_text, partial_link_text, name, tag_name, xpath";
  793. }
  794. }
  795. =head2 find_elements
  796. Description:
  797. Search for multiple elements on the page, starting from the document root.
  798. The located elements will be returned as an array of WebElement object.
  799. Input: 2 (1 optional)
  800. Required:
  801. STRING - The search target.
  802. Optional:
  803. STRING - Locator scheme to use to search the element, available schemes:
  804. {class, class_name, css, id, link, link_text, partial_link_text,
  805. tag_name, name, xpath}
  806. Defaults to 'xpath'.
  807. Output:
  808. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects
  809. Usage:
  810. $driver->find_elements("//input");
  811. =cut
  812. sub find_elements {
  813. my ( $self, $query, $method ) = @_;
  814. if ( not defined $query ) {
  815. return 'Search string to find element not provided.';
  816. }
  817. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  818. if (defined $using) {
  819. my $res = { 'command' => 'findElements' };
  820. my $params = { 'using' => $using, 'value' => $query };
  821. my $ret_data = $self->_execute_command( $res, $params );
  822. my $elem_obj_arr;
  823. my $i = 0;
  824. foreach (@$ret_data) {
  825. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  826. $i++;
  827. }
  828. return $elem_obj_arr;
  829. }
  830. else {
  831. croak "Bad method, expected - class, class_name, css, id, link,
  832. link_text, partial_link_text, name, tag_name, xpath";
  833. }
  834. }
  835. =head2 find_child_element
  836. Description:
  837. Search for an element on the page, starting from the identified element. The
  838. located element will be returned as a WebElement object.
  839. Input: 3 (1 optional)
  840. Required:
  841. Selenium::Remote::WebElement - WebElement object from where you want to
  842. start searching.
  843. STRING - The search target.
  844. Optional:
  845. STRING - Locator scheme to use to search the element, available schemes:
  846. {class, class_name, css, id, link, link_text, partial_link_text,
  847. tag_name, name, xpath}
  848. Defaults to 'xpath'.
  849. Output:
  850. Selenium::Remote::WebElement - WebElement Object
  851. Usage:
  852. my $elem1 = $driver->find_element("//select[\@name='ned']");
  853. my $child = $driver->find_child_element($elem1, "//option[\@value='es_ar']");
  854. =cut
  855. sub find_child_element {
  856. my ( $self, $elem, $query, $method ) = @_;
  857. if ( ( not defined $elem ) || ( not defined $query ) ) {
  858. return "Missing parameters";
  859. }
  860. my $using = ( defined $method ) ? $method : 'xpath';
  861. if (exists FINDERS->{$using}) {
  862. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  863. my $params = { 'using' => $using, 'value' => $query };
  864. my $ret_data = $self->_execute_command( $res, $params );
  865. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  866. }
  867. else {
  868. croak "Bad method, expected - class, class_name, css, id, link,
  869. link_text, partial_link_text, name, tag_name, xpath";
  870. }
  871. }
  872. =head2 find_child_elements
  873. Description:
  874. Search for multiple element on the page, starting from the identified
  875. element. The located elements will be returned as an array of WebElement
  876. objects.
  877. Input: 3 (1 optional)
  878. Required:
  879. Selenium::Remote::WebElement - WebElement object from where you want to
  880. start searching.
  881. STRING - The search target.
  882. Optional:
  883. STRING - Locator scheme to use to search the element, available schemes:
  884. {class, class_name, css, id, link, link_text, partial_link_text,
  885. tag_name, name, xpath}
  886. Defaults to 'xpath'.
  887. Output:
  888. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects.
  889. Usage:
  890. my $elem1 = $driver->find_element("//select[\@name='ned']");
  891. my $child = $driver->find_child_elements($elem1, "//option");
  892. =cut
  893. sub find_child_elements {
  894. my ( $self, $elem, $query, $method ) = @_;
  895. if ( ( not defined $elem ) || ( not defined $query ) ) {
  896. return "Missing parameters";
  897. }
  898. my $using = ( defined $method ) ? $method : 'xpath';
  899. if (exists FINDERS->{$using}) {
  900. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  901. my $params = { 'using' => $using, 'value' => $query };
  902. my $ret_data = $self->_execute_command( $res, $params );
  903. my $elem_obj_arr;
  904. my $i = 0;
  905. foreach (@$ret_data) {
  906. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  907. $i++;
  908. }
  909. return $elem_obj_arr;
  910. }
  911. else {
  912. croak "Bad method, expected - class, class_name, css, id, link,
  913. link_text, partial_link_text, name, tag_name, xpath";
  914. }
  915. }
  916. =head2 get_active_element
  917. Description:
  918. Get the element on the page that currently has focus.. The located element
  919. will be returned as a WebElement object.
  920. Output:
  921. Selenium::Remote::WebElement - WebElement Object
  922. Usage:
  923. $driver->get_active_element();
  924. =cut
  925. sub get_active_element {
  926. my ($self) = @_;
  927. my $res = { 'command' => 'getActiveElement' };
  928. return $self->_execute_command($res);
  929. }
  930. # Not yet supported on the server
  931. sub describe_element {
  932. my ( $self, $element ) = @_;
  933. #if (not defined $element) {
  934. # return "Element not provided";
  935. #}
  936. #my $res = {'command' => 'desribeElement', 'name' => $element};
  937. #return $self->_execute_command($res);
  938. return "Not yet supported";
  939. }
  940. =head2 send_modifier
  941. Description:
  942. Send an event to the active element to depress or release a modifier key.
  943. Input: 2
  944. Required:
  945. value - String - The modifier key event to be sent. This key must be one 'Ctrl','Shift','Alt',' or 'Command'/'Meta' as defined by the send keys command
  946. isdown - Boolean/String - Whether to generate a key down or key up
  947. Usage:
  948. $driver->send_modifier('Alt','down');
  949. $elem->send_keys('c');
  950. $driver->send_modifier('Alt','up');
  951. or
  952. $driver->send_modifier('Alt',1);
  953. $elem->send_keys('c');
  954. $driver->send_modifier('Alt',0);
  955. =cut
  956. sub send_modifier {
  957. my ($self,$modifier,$isdown) = @_;
  958. if($isdown =~ /(down|up)/) {
  959. $isdown = $isdown =~ /down/ ? 1:0;
  960. }
  961. my $res = {'command' => 'sendModifier'};
  962. my $params = {value => $modifier,
  963. isdown => $isdown};
  964. return $self->_execute_command($res,$params);
  965. }
  966. =head2 compare_elements
  967. Description:
  968. Test if two element IDs refer to the same DOM element.
  969. Input: 2
  970. Required:
  971. Selenium::Remote::WebElement - WebElement Object
  972. Selenium::Remote::WebElement - WebElement Object
  973. Output:
  974. BOOLEAN
  975. Usage:
  976. $driver->compare_elements($elem_obj1, $elem_obj2);
  977. =cut
  978. sub compare_elements {
  979. my ($self, $elem1, $elem2) = @_;
  980. my $res = { 'command' => 'elementEquals',
  981. 'id' => $elem1->{id},
  982. 'other' => $elem2->{id}
  983. };
  984. return $self->_execute_command($res);
  985. }
  986. 1;
  987. __END__
  988. =head1 SEE ALSO
  989. For more information about Selenium , visit the website at
  990. L<http://code.google.com/p/selenium/>.
  991. =head1 BUGS
  992. The Selenium issue tracking system is available online at
  993. L<http://github.com/aivaturi/Selenium-Remote-Driver/issues>.
  994. =head1 AUTHOR
  995. Perl Bindings for Selenium Remote Driver by Aditya Ivaturi <ivaturi@gmail.com>
  996. =head1 LICENSE
  997. Copyright (c) 2010 Aditya Ivaturi
  998. Licensed under the Apache License, Version 2.0 (the "License");
  999. you may not use this file except in compliance with the License.
  1000. You may obtain a copy of the License at
  1001. http://www.apache.org/licenses/LICENSE-2.0
  1002. Unless required by applicable law or agreed to in writing, software
  1003. distributed under the License is distributed on an "AS IS" BASIS,
  1004. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1005. See the License for the specific language governing permissions and
  1006. limitations under the License.