Driver.pm 37 KB

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