1
0

Driver.pm 39 KB

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