Driver.pm 36 KB

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