1
0

Driver.pm 38 KB

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