Driver.pm 42 KB

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