Driver.pm 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  1. package Selenium::Remote::Driver;
  2. use strict;
  3. use warnings;
  4. use Carp;
  5. our @CARP_NOT;
  6. use MIME::Base64;
  7. use IO::Compress::Zip qw(zip $ZipError) ;
  8. use Selenium::Remote::RemoteConnection;
  9. use Selenium::Remote::Commands;
  10. use Selenium::Remote::WebElement;
  11. use constant FINDERS => {
  12. class => 'class name',
  13. class_name => 'class name',
  14. css => 'css selector',
  15. id => 'id',
  16. link => 'link text',
  17. link_text => 'link text',
  18. name => 'name',
  19. partial_link_text => 'partial link text',
  20. tag_name => 'tag name',
  21. xpath => 'xpath',
  22. };
  23. our $VERSION = "0.15";
  24. =head1 NAME
  25. Selenium::Remote::Driver - Perl Client for Selenium Remote Driver
  26. =cut
  27. =head1 SYNOPSIS
  28. use Selenium::Remote::Driver;
  29. my $driver = new Selenium::Remote::Driver;
  30. $driver->get('http://www.google.com');
  31. print $driver->get_title();
  32. $driver->quit();
  33. =cut
  34. =head1 DESCRIPTION
  35. Selenium is a test tool that allows you to write
  36. automated web application UI tests in any programming language against
  37. any HTTP website using any mainstream JavaScript-enabled browser. This module is
  38. an implementation of the client for the Remote driver that Selenium provides.
  39. You can find bindings for other languages at this location:
  40. L<http://code.google.com/p/selenium/>
  41. This module sends commands directly to the Server using HTTP. Using this module
  42. together with the Selenium Server, you can automatically control any supported
  43. browser. To use this module, you need to have already downloaded and started
  44. the Selenium Server (Selenium Server is a Java application).
  45. =cut
  46. =head1 USAGE (read this first)
  47. =head2 Remote Driver Response
  48. Selenium::Remote::Driver uses the L<JsonWireProtocol|http://code.google.com/p/selenium/wiki/JsonWireProtocol> to communicate with the
  49. Selenium Server. If an error occurs while executing the command then the server
  50. sends back an HTTP error code with a JSON encoded reponse that indicates the
  51. 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
  52. associated with this code. If no error occurred, then the subroutine called will
  53. return the value sent back from the server (if a return value was sent).
  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: (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. 'accept_ssl_certs' - <boolean> - whether SSL certs should be accepted, default is true.
  87. 'auto_close' - <boolean> - whether driver should end session on remote
  88. server on close.
  89. 'extra_capabilities' - HASH of extra capabilities
  90. 'proxy' - HASH - Proxy configuration with the following keys:
  91. 'proxyType' - <string> - REQUIRED, Possible values are:
  92. direct - A direct connection - no proxy in use,
  93. manual - Manual proxy settings configured, e.g. setting a proxy for HTTP, a proxy for FTP, etc,
  94. pac - Proxy autoconfiguration from a URL,
  95. autodetect - proxy autodetection, probably with WPAD,
  96. system - Use system settings
  97. 'proxyAutoconfigUrl' - <string> - REQUIRED if proxyType is 'pac', ignored otherwise. Expected format: http://hostname.com:1234/pacfile.
  98. 'ftpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  99. 'httpProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  100. 'sslProxy' - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  101. If no values are provided, then these defaults will be assumed:
  102. 'remote_server_addr' => 'localhost'
  103. 'port' => '4444'
  104. 'browser_name' => 'firefox'
  105. 'version' => ''
  106. 'platform' => 'ANY'
  107. 'javascript' => 1
  108. 'auto_close' => 1
  109. Output:
  110. Remote Driver object
  111. Usage:
  112. my $driver = new Selenium::Remote::Driver;
  113. or
  114. my $driver = new Selenium::Remote::Driver('browser_name' => 'firefox',
  115. 'platform' => 'MAC');
  116. or
  117. my $driver = new Selenium::Remote::Driver('remote_server_addr' => '10.10.1.1',
  118. 'port' => '2222',
  119. auto_close => 0
  120. );
  121. or
  122. my $driver = new Selenium::Remote::Driver('browser_name' => 'chrome',
  123. 'platform' => 'VISTA',
  124. 'extra_capabilities' => {'chrome.switches' => ["--user-data-dir=$ENV{LOCALAPPDATA}\\Google\\Chrome\\User Data"],
  125. 'chrome.prefs' => {'download.default_directory' =>'/home/user/tmp', 'download.prompt_for_download' =>1 }
  126. },
  127. );
  128. or
  129. my $driver = Selenium::Remote::Driver->new('proxy' => {'proxyType' => 'manual', 'httpProxy' => 'myproxy.com:1234'});
  130. =cut
  131. sub new {
  132. my ( $class, %args ) = @_;
  133. my $ress = new Selenium::Remote::Commands;
  134. # Set the defaults if user doesn't send any
  135. my $self = {
  136. remote_server_addr => delete $args{remote_server_addr} || 'localhost',
  137. browser_name => delete $args{browser_name} || 'firefox',
  138. platform => delete $args{platform} || 'ANY',
  139. port => delete $args{port} || '4444',
  140. version => delete $args{version} || '',
  141. session_id => undef,
  142. remote_conn => undef,
  143. commands => $ress,
  144. auto_close => 1, # by default we will close remote session on DESTROY
  145. pid => $$,
  146. };
  147. bless $self, $class or die "Can't bless $class: $!";
  148. # check for javascript
  149. if ( defined $args{javascript} ) {
  150. if ( $args{javascript} ) {
  151. $self->{javascript} = JSON::true;
  152. }
  153. else {
  154. $self->{javascript} = JSON::false;
  155. }
  156. }
  157. else {
  158. $self->{javascript} = JSON::true;
  159. }
  160. # check for acceptSslCerts
  161. if ( defined $args{accept_ssl_certs} ) {
  162. if ( $args{accept_ssl_certs} ) {
  163. $self->{accept_ssl_certs} = JSON::true;
  164. }
  165. else {
  166. $self->{accept_ssl_certs} = JSON::false;
  167. }
  168. }
  169. else {
  170. $self->{accept_ssl_certs} = JSON::true;
  171. }
  172. # check for proxy
  173. if ( defined $args{proxy} ) {
  174. if ($args{proxy}{proxyType} eq 'pac') {
  175. if (not defined $args{proxy}{proxyAutoconfigUrl}) {
  176. croak "proxyAutoconfigUrl not provided\n";
  177. } elsif (not ($args{proxy}{proxyAutoconfigUrl} =~ /^http/g)) {
  178. croak "proxyAutoconfigUrl should be of format http://";
  179. }
  180. }
  181. $self->{proxy} = $args{proxy};
  182. }
  183. # Connect to remote server & establish a new session
  184. $self->{remote_conn} =
  185. new Selenium::Remote::RemoteConnection( $self->{remote_server_addr},
  186. $self->{port} );
  187. $self->new_session(delete $args{extra_capabilities});
  188. if ( !( defined $self->{session_id} ) ) {
  189. croak "Could not establish a session with the remote server\n";
  190. }
  191. return $self;
  192. }
  193. sub DESTROY {
  194. my ($self) = @_;
  195. return if $$ != $self->{pid};
  196. $self->quit() if ($self->{auto_close} && defined $self->{session_id});
  197. }
  198. # This is an internal method used the Driver & is not supposed to be used by
  199. # end user. This method is used by Driver to set up all the parameters
  200. # (url & JSON), send commands & receive processed response from the server.
  201. sub _execute_command {
  202. my ( $self, $res, $params ) = @_;
  203. $res->{'session_id'} = $self->{'session_id'};
  204. my $resource = $self->{commands}->get_params($res);
  205. if ($resource) {
  206. my $resp = $self->{remote_conn}
  207. ->request( $resource->{'method'}, $resource->{'url'}, $params );
  208. if(ref($resp) eq 'HASH') {
  209. if($resp->{cmd_status} eq 'OK') {
  210. return $resp->{cmd_return};
  211. } else {
  212. my $msg = "Error while executing command";
  213. if($resp->{cmd_error}) {
  214. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  215. } else {
  216. if(ref($resp->{cmd_return}) eq 'HASH') {
  217. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  218. if $resp->{cmd_return}->{error}->{msg};
  219. $msg .= ": $resp->{cmd_return}->{message}"
  220. if $resp->{cmd_return}->{message};
  221. } else {
  222. $msg .= ": $resp->{cmd_return}";
  223. }
  224. }
  225. croak $msg;
  226. }
  227. }
  228. return $resp;
  229. }
  230. else {
  231. croak "Couldn't retrieve command settings properly\n";
  232. }
  233. }
  234. # A method that is used by the Driver itself. It'll be called to set the
  235. # desired capabilities on the server.
  236. sub new_session {
  237. my ($self, $extra_capabilities) = @_;
  238. $extra_capabilities ||= {};
  239. my $args = {
  240. 'desiredCapabilities' => {
  241. 'browserName' => $self->{browser_name},
  242. 'platform' => $self->{platform},
  243. 'javascriptEnabled' => $self->{javascript},
  244. 'version' => $self->{version},
  245. 'acceptSslCerts' => $self->{accept_ssl_certs},
  246. %$extra_capabilities,
  247. },
  248. };
  249. if (defined $self->{proxy}) {
  250. $args->{desiredCapabilities}->{proxy} = $self->{proxy};
  251. }
  252. my $resp =
  253. $self->{remote_conn}
  254. ->request( $self->{commands}->{'newSession'}->{'method'},
  255. $self->{commands}->{'newSession'}->{'url'}, $args, );
  256. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  257. $self->{session_id} = $resp->{'sessionId'};
  258. }
  259. else {
  260. croak "Could not create new session";
  261. }
  262. }
  263. =head2 debug_on
  264. Description:
  265. Turns on debugging mode and the driver will print extra info like request
  266. and response to stdout. Useful, when you want to see what is being sent to
  267. the server & what response you are getting back.
  268. Usage:
  269. $driver->debug_on;
  270. =cut
  271. sub debug_on {
  272. my ($self) = @_;
  273. $self->{'remote_conn'}->{'debug'} = 1;
  274. }
  275. =head2 debug_off
  276. Description:
  277. Turns off the debugging mode.
  278. Usage:
  279. $driver->debug_off;
  280. =cut
  281. sub debug_off {
  282. my ($self) = @_;
  283. $self->{'remote_conn'}->{'debug'} = 0;
  284. }
  285. =head2 get_sessions
  286. Description:
  287. Returns a list of the currently active sessions. Each session will be
  288. returned as an array of Hashes with the following keys:
  289. 'id' : The session ID
  290. 'capabilities: An object describing session's capabilities
  291. Output:
  292. Array of Hashes
  293. Usage:
  294. print Dumper $driver->get_sessions();
  295. =cut
  296. sub get_sessions{
  297. my ($self) = @_;
  298. my $res = { 'command' => 'getSessions' };
  299. return $self->_execute_command($res);
  300. }
  301. =head2 status
  302. Description:
  303. Query the server's current status. All server implementations
  304. should return two basic objects describing the server's current
  305. platform and when the server was built.
  306. Output:
  307. Hash ref
  308. Usage:
  309. print Dumper $driver->status;
  310. =cut
  311. sub status {
  312. my ($self) = @_;
  313. my $res = { 'command' => 'status' };
  314. return $self->_execute_command($res);
  315. }
  316. =head2 get_alert_text
  317. Description:
  318. Gets the text of the currently displayed JavaScript alert(), confirm()
  319. or prompt() dialog.
  320. Example
  321. my $string = $driver->get_alert_text;
  322. =cut
  323. sub get_alert_text {
  324. my ($self) = @_;
  325. my $res = { 'command' => 'getAlertText' };
  326. return $self->_execute_command($res);
  327. }
  328. =head2 send_keys_to_active_element
  329. Description:
  330. Send a sequence of key strokes to the active element. This command is
  331. similar to the send keys command in every aspect except the implicit
  332. termination: The modifiers are not released at the end of the call.
  333. Rather, the state of the modifier keys is kept between calls, so mouse
  334. interactions can be performed while modifier keys are depressed.
  335. Input: 1
  336. Required:
  337. {ARRAY | STRING} - Array of strings or a string.
  338. Usage:
  339. $driver->send_keys_to_active_element('abcd', 'efg');
  340. $driver->send_keys_to_active_element('hijk');
  341. or
  342. # include the WDKeys module
  343. use Selenium::Remote::WDKeys;
  344. .
  345. .
  346. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  347. =cut
  348. sub send_keys_to_active_element {
  349. my ($self, @strings) = @_;
  350. my $res = { 'command' => 'sendKeysToActiveElement' };
  351. my $params = {
  352. 'value' => \@strings,
  353. };
  354. return $self->_execute_command($res, $params);
  355. }
  356. =head2 send_keys_to_alert
  357. Synonymous with send_keys_to_prompt
  358. =cut
  359. sub send_keys_to_alert {
  360. return shift->send_keys_to_prompt(@_);
  361. }
  362. =head2 send_keys_to_prompt
  363. Description:
  364. Sends keystrokes to a JavaScript prompt() dialog.
  365. Input:
  366. {string} keys to send
  367. Example:
  368. $driver->send_keys_to_prompt('hello world');
  369. or
  370. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  371. $driver->send_keys_to_alert("Larry Wall");
  372. $driver->accept_alert;
  373. =cut
  374. sub send_keys_to_prompt {
  375. my ($self,$keys) = @_;
  376. my $res = { 'command' => 'sendKeysToPrompt' };
  377. my $params = { 'text' => $keys };
  378. return $self->_execute_command($res,$params);
  379. }
  380. =head2 accept_alert
  381. Description:
  382. Accepts the currently displayed alert dialog. Usually, this is
  383. equivalent to clicking the 'OK' button in the dialog.
  384. Example:
  385. $driver->accept_alert;
  386. =cut
  387. sub accept_alert {
  388. my ($self) = @_;
  389. my $res = { 'command' => 'acceptAlert' };
  390. return $self->_execute_command($res);
  391. }
  392. =head2 dismiss_alert
  393. Description:
  394. Dismisses the currently displayed alert dialog. For comfirm()
  395. and prompt() dialogs, this is equivalent to clicking the
  396. 'Cancel' button. For alert() dialogs, this is equivalent to
  397. clicking the 'OK' button.
  398. Example:
  399. $driver->dismiss_alert;
  400. =cut
  401. sub dismiss_alert {
  402. my ($self) = @_;
  403. my $res = { 'command' => 'dismissAlert' };
  404. return $self->_execute_command($res);
  405. }
  406. =head2 mouse_move_to_location
  407. Description:
  408. Move the mouse by an offset of the specificed element. If no
  409. element is specified, the move is relative to the current mouse
  410. cursor. If an element is provided but no offset, the mouse will be
  411. moved to the center of the element. If the element is not visible,
  412. it will be scrolled into view.
  413. Output:
  414. STRING -
  415. Usage:
  416. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  417. # 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.
  418. # 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.
  419. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  420. =cut
  421. sub mouse_move_to_location {
  422. my ($self, %params) = @_;
  423. $params{element} = $params{element}{id} if exists $params{element};
  424. my $res = { 'command' => 'mouseMoveToLocation' };
  425. return $self->_execute_command($res, \%params);
  426. }
  427. =head2 move_to
  428. Synonymous with mouse_move_to_location
  429. =cut
  430. sub move_to {
  431. return shift->mouse_move_to_location(@_);
  432. }
  433. =head2 get_capabilities
  434. Description:
  435. Retrieve the capabilities of the specified session.
  436. Output:
  437. HASH of all the capabilities.
  438. Usage:
  439. my $capab = $driver->get_capabilities();
  440. print Dumper($capab);
  441. =cut
  442. sub get_capabilities {
  443. my $self = shift;
  444. my $res = {'command' => 'getCapabilities'};
  445. return $self->_execute_command($res);
  446. }
  447. =head2 set_timeout
  448. Description:
  449. Configure the amount of time that a particular type of operation can execute
  450. for before they are aborted and a |Timeout| error is returned to the client.
  451. Input:
  452. type - <STRING> - The type of operation to set the timeout for.
  453. Valid values are:
  454. "script" : for script timeouts,
  455. "implicit" : for modifying the implicit wait timeout
  456. "page load" : for setting a page load timeout.
  457. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  458. commands are permitted to run.
  459. Usage:
  460. $driver->set_timeout('script', 1000);
  461. =cut
  462. sub set_timeout {
  463. my ($self, $type, $ms) = @_;
  464. if (not defined $type or not defined $ms)
  465. {
  466. croak "Expecting type & timeout in ms";
  467. }
  468. my $res = {'command' => 'setTimeout'};
  469. my $params = {'type' => $type, 'ms' => $ms};
  470. return $self->_execute_command($res, $params);
  471. }
  472. =head2 set_async_script_timeout
  473. Description:
  474. Set the amount of time, in milliseconds, that asynchronous scripts executed
  475. by execute_async_script() are permitted to run before they are
  476. aborted and a |Timeout| error is returned to the client.
  477. Input:
  478. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  479. commands are permitted to run.
  480. Usage:
  481. $driver->set_async_script_timeout(1000);
  482. =cut
  483. sub set_async_script_timeout {
  484. my ($self, $ms) = @_;
  485. if (not defined $ms)
  486. {
  487. croak "Expecting timeout in ms";
  488. }
  489. my $res = {'command' => 'setAsyncScriptTimeout'};
  490. my $params = {'ms' => $ms};
  491. return $self->_execute_command($res, $params);
  492. }
  493. =head2 set_implicit_wait_timeout
  494. Description:
  495. Set the amount of time the driver should wait when searching for elements.
  496. When searching for a single element, the driver will poll the page until
  497. an element is found or the timeout expires, whichever occurs first.
  498. When searching for multiple elements, the driver should poll the page until
  499. at least one element is found or the timeout expires, at which point it
  500. will return an empty list. If this method is never called, the driver will
  501. default to an implicit wait of 0ms.
  502. Input:
  503. Time in milliseconds.
  504. Output:
  505. Server Response Hash with no data returned back from the server.
  506. Usage:
  507. $driver->set_implicit_wait_timeout(10);
  508. =cut
  509. sub set_implicit_wait_timeout {
  510. my ($self, $ms) = @_;
  511. my $res = {'command' => 'setImplicitWaitTimeout'};
  512. my $params = {'ms' => $ms};
  513. return $self->_execute_command($res, $params);
  514. }
  515. =head2 close
  516. Description:
  517. Close the current window.
  518. Usage:
  519. $driver->close();
  520. or
  521. #close a popup window
  522. my $handles = $driver->get_window_handles;
  523. $driver->switch_to_window($handles->[1]);
  524. $driver->close();
  525. $driver->switch_to_window($handles->[0]);
  526. =cut
  527. sub close {
  528. my $self = shift;
  529. my $res = { 'command' => 'close' };
  530. $self->_execute_command($res);
  531. }
  532. =head2 quit
  533. Description:
  534. Delete the session & close open browsers.
  535. Usage:
  536. $driver->quit();
  537. =cut
  538. sub quit {
  539. my $self = shift;
  540. my $res = { 'command' => 'quit' };
  541. $self->_execute_command($res);
  542. $self->{session_id} = undef;
  543. }
  544. =head2 get_current_window_handle
  545. Description:
  546. Retrieve the current window handle.
  547. Output:
  548. STRING - the window handle
  549. Usage:
  550. print $driver->get_current_window_handle();
  551. =cut
  552. sub get_current_window_handle {
  553. my $self = shift;
  554. my $res = { 'command' => 'getCurrentWindowHandle' };
  555. return $self->_execute_command($res);
  556. }
  557. =head2 get_window_handles
  558. Description:
  559. Retrieve the list of window handles used in the session.
  560. Output:
  561. ARRAY of STRING - list of the window handles
  562. Usage:
  563. print Dumper $driver->get_window_handles;
  564. or
  565. # get popup, close, then back
  566. my $handles = $driver->get_window_handles;
  567. $driver->switch_to_window($handles->[1]);
  568. $driver->close;
  569. $driver->switch_to_window($handles->[0]);
  570. =cut
  571. sub get_window_handles {
  572. my $self = shift;
  573. my $res = { 'command' => 'getWindowHandles' };
  574. return $self->_execute_command($res);
  575. }
  576. =head2 get_window_size
  577. Description:
  578. Retrieve the window size
  579. Input:
  580. STRING - <optional> - window handle (default is 'current' window)
  581. Output:
  582. HASH - containing keys 'height' & 'width'
  583. Usage:
  584. my $window_size = $driver->get_window_size();
  585. print $window_size->{'height'}, $window_size->('width');
  586. =cut
  587. sub get_window_size {
  588. my ( $self, $window ) = @_;
  589. $window = (defined $window)?$window:'current';
  590. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  591. return $self->_execute_command($res);
  592. }
  593. =head2 get_window_position
  594. Description:
  595. Retrieve the window position
  596. Input:
  597. STRING - <optional> - window handle (default is 'current' window)
  598. Output:
  599. HASH - containing keys 'x' & 'y'
  600. Usage:
  601. my $window_size = $driver->get_window_position();
  602. print $window_size->{'x'}, $window_size->('y');
  603. =cut
  604. sub get_window_position {
  605. my ( $self, $window ) = @_;
  606. $window = (defined $window)?$window:'current';
  607. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  608. return $self->_execute_command($res);
  609. }
  610. =head2 get_current_url
  611. Description:
  612. Retrieve the url of the current page
  613. Output:
  614. STRING - url
  615. Usage:
  616. print $driver->get_current_url();
  617. =cut
  618. sub get_current_url {
  619. my $self = shift;
  620. my $res = { 'command' => 'getCurrentUrl' };
  621. return $self->_execute_command($res);
  622. }
  623. =head2 navigate
  624. Description:
  625. Navigate to a given url. This is same as get() method.
  626. Input:
  627. STRING - url
  628. Usage:
  629. $driver->navigate('http://www.google.com');
  630. =cut
  631. sub navigate {
  632. my ( $self, $url ) = @_;
  633. $self->get($url);
  634. }
  635. =head2 get
  636. Description:
  637. Navigate to a given url
  638. Input:
  639. STRING - url
  640. Usage:
  641. $driver->get('http://www.google.com');
  642. =cut
  643. sub get {
  644. my ( $self, $url ) = @_;
  645. my $res = { 'command' => 'get' };
  646. my $params = { 'url' => $url };
  647. return $self->_execute_command( $res, $params );
  648. }
  649. =head2 get_title
  650. Description:
  651. Get the current page title
  652. Output:
  653. STRING - Page title
  654. Usage:
  655. print $driver->get_title();
  656. =cut
  657. sub get_title {
  658. my $self = shift;
  659. my $res = { 'command' => 'getTitle' };
  660. return $self->_execute_command($res);
  661. }
  662. =head2 go_back
  663. Description:
  664. Equivalent to hitting the back button on the browser.
  665. Usage:
  666. $driver->go_back();
  667. =cut
  668. sub go_back {
  669. my $self = shift;
  670. my $res = { 'command' => 'goBack' };
  671. return $self->_execute_command($res);
  672. }
  673. =head2 go_forward
  674. Description:
  675. Equivalent to hitting the forward button on the browser.
  676. Usage:
  677. $driver->go_forward();
  678. =cut
  679. sub go_forward {
  680. my $self = shift;
  681. my $res = { 'command' => 'goForward' };
  682. return $self->_execute_command($res);
  683. }
  684. =head2 refresh
  685. Description:
  686. Reload the current page.
  687. Usage:
  688. $driver->refresh();
  689. =cut
  690. sub refresh {
  691. my $self = shift;
  692. my $res = { 'command' => 'refresh' };
  693. return $self->_execute_command($res);
  694. }
  695. =head2 javascript
  696. Description:
  697. returns true if javascript is enabled in the driver.
  698. Usage:
  699. if ($driver->javascript) { ...; }
  700. =cut
  701. sub javascript {
  702. my $self = shift;
  703. return $self->{javascript} == JSON::true;
  704. }
  705. =head2 execute_async_script
  706. Description:
  707. Inject a snippet of JavaScript into the page for execution in the context
  708. of the currently selected frame. The executed script is assumed to be
  709. asynchronous and must signal that is done by invoking the provided
  710. callback, which is always provided as the final argument to the function.
  711. The value to this callback will be returned to the client.
  712. Asynchronous script commands may not span page loads. If an unload event
  713. is fired while waiting for a script result, an error should be returned
  714. to the client.
  715. Input: 2 (1 optional)
  716. Required:
  717. STRING - Javascript to execute on the page
  718. Optional:
  719. ARRAY - list of arguments that need to be passed to the script.
  720. Output:
  721. {*} - Varied, depending on the type of result expected back from the script.
  722. Usage:
  723. my $script = q{
  724. var arg1 = arguments[0];
  725. var callback = arguments[arguments.length-1];
  726. var elem = window.document.findElementById(arg1);
  727. callback(elem);
  728. };
  729. my $callback = q{return arguments[0];};
  730. my $elem = $driver->execute_async_script($script,'myid',$callback);
  731. $elem->click;
  732. =cut
  733. sub execute_async_script {
  734. my ( $self, $script, @args ) = @_;
  735. if ($self->javascript) {
  736. if ( not defined $script ) {
  737. croak 'No script provided';
  738. }
  739. my $res = { 'command' => 'executeAsyncScript' };
  740. # Check the args array if the elem obj is provided & replace it with
  741. # JSON representation
  742. for (my $i=0; $i<@args; $i++) {
  743. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  744. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  745. }
  746. }
  747. my $params = {'script' => $script, 'args' => \@args};
  748. my $ret = $self->_execute_command($res, $params);
  749. # replace any ELEMENTS with WebElement
  750. if (ref($ret) and (ref($ret) eq 'HASH') and exists $ret->{'ELEMENT'}) {
  751. $ret =
  752. new Selenium::Remote::WebElement(
  753. $ret->{ELEMENT}, $self);
  754. }
  755. return $ret;
  756. }
  757. else {
  758. croak 'Javascript is not enabled on remote driver instance.';
  759. }
  760. }
  761. =head2 execute_script
  762. Description:
  763. Inject a snippet of JavaScript into the page and return its result.
  764. WebElements that should be passed to the script as an argument should be
  765. specified in the arguments array as WebElement object. Likewise,
  766. any WebElements in the script result will be returned as WebElement object.
  767. Input: 2 (1 optional)
  768. Required:
  769. STRING - Javascript to execute on the page
  770. Optional:
  771. ARRAY - list of arguments that need to be passed to the script.
  772. Output:
  773. {*} - Varied, depending on the type of result expected back from the script.
  774. Usage:
  775. my $script = q{
  776. var arg1 = arguments[0];
  777. var elem = window.document.findElementById(arg1);
  778. return elem;
  779. };
  780. my $elem = $driver->execute_script($script,'myid');
  781. $elem->click;
  782. =cut
  783. sub execute_script {
  784. my ( $self, $script, @args ) = @_;
  785. if ($self->javascript) {
  786. if ( not defined $script ) {
  787. croak 'No script provided';
  788. }
  789. my $res = { 'command' => 'executeScript' };
  790. # Check the args array if the elem obj is provided & replace it with
  791. # JSON representation
  792. for (my $i=0; $i<@args; $i++) {
  793. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  794. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  795. }
  796. }
  797. my $params = {'script' => $script, 'args' => [@args]};
  798. my $ret = $self->_execute_command($res, $params);
  799. return $self->_convert_to_webelement($ret);
  800. }
  801. else {
  802. croak 'Javascript is not enabled on remote driver instance.';
  803. }
  804. }
  805. # _convert_to_webelement
  806. # An internal method used to traverse a data structure
  807. # and convert any ELEMENTS with WebElements
  808. sub _convert_to_webelement {
  809. my ($self, $ret ) = @_;
  810. if (ref($ret) and (ref($ret) eq 'HASH')) {
  811. if((keys %$ret==1) and exists $ret->{'ELEMENT'}) {
  812. # replace an ELEMENT with WebElement
  813. return new Selenium::Remote::WebElement($ret->{ELEMENT}, $self);
  814. }
  815. my %hash;
  816. foreach my $key (keys %$ret) {
  817. $hash{$key}=$self->_convert_to_webelement($ret->{$key});
  818. }
  819. return \%hash;
  820. }
  821. if(ref($ret) and (ref($ret) eq 'ARRAY')) {
  822. my @array = map {$self->_convert_to_webelement($_)} @$ret;
  823. return \@array;
  824. }
  825. return $ret;
  826. }
  827. =head2 screenshot
  828. Description:
  829. Get a screenshot of the current page as a base64 encoded image.
  830. Output:
  831. STRING - base64 encoded image
  832. Usage:
  833. print $driver->screenshot();
  834. or
  835. require MIME::Base64;
  836. open(FH,'>','screenshot.png');
  837. binmode FH;
  838. my $png_base64 = $driver->screenshot();
  839. print FH MIME::Base64::decode_base64($png_base64);
  840. close FH;
  841. =cut
  842. sub screenshot {
  843. my ($self) = @_;
  844. my $res = { 'command' => 'screenshot' };
  845. return $self->_execute_command($res);
  846. }
  847. =head2 available_engines
  848. Description:
  849. List all available engines on the machine. To use an engine, it has to be present in this list.
  850. Output:
  851. {Array.<string>} A list of available engines
  852. Usage:
  853. print Dumper $driver->available_engines;
  854. =cut
  855. sub available_engines {
  856. my ($self) = @_;
  857. my $res = { 'command' => 'availableEngines' };
  858. return $self->_execute_command($res);
  859. }
  860. =head2 switch_to_frame
  861. Description:
  862. Change focus to another frame on the page. If the frame ID is null, the
  863. server will switch to the page's default content. You can also switch to a
  864. WebElement, for e.g. you can find an iframe using find_element & then
  865. provide that as an input to this method. Also see e.g.
  866. Input: 1
  867. Required:
  868. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  869. mentioned.
  870. Usage:
  871. $driver->switch_to_frame('frame_1');
  872. or
  873. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  874. =cut
  875. sub switch_to_frame {
  876. my ( $self, $id ) = @_;
  877. my $json_null = JSON::null;
  878. my $params;
  879. $id = ( defined $id ) ? $id : $json_null;
  880. my $res = { 'command' => 'switchToFrame' };
  881. if (ref $id eq 'Selenium::Remote::WebElement') {
  882. $params = { 'id' => {'ELEMENT' => $id->{'id'}}};
  883. } else {
  884. $params = { 'id' => $id };
  885. }
  886. return $self->_execute_command( $res, $params );
  887. }
  888. =head2 switch_to_window
  889. Description:
  890. Change focus to another window. The window to change focus to may be
  891. specified by its server assigned window handle, or by the value of its name
  892. attribute.
  893. Input: 1
  894. Required:
  895. STRING - Window handle or the Window name
  896. Usage:
  897. $driver->switch_to_window('MY Homepage');
  898. or
  899. # close a popup window and switch back
  900. my $handles = $driver->get_window_handles;
  901. $driver->switch_to_window($handles->[1]);
  902. $driver->close;
  903. $driver->switch_to_window($handles->[0]);
  904. =cut
  905. sub switch_to_window {
  906. my ( $self, $name ) = @_;
  907. if ( not defined $name ) {
  908. return 'Window name not provided';
  909. }
  910. my $res = { 'command' => 'switchToWindow' };
  911. my $params = { 'name' => $name };
  912. return $self->_execute_command( $res, $params );
  913. }
  914. =head2 get_speed
  915. Description:
  916. Get the current user input speed. The actual input speed is still browser
  917. specific and not covered by the Driver.
  918. Output:
  919. STRING - One of these: SLOW, MEDIUM, FAST
  920. Usage:
  921. print $driver->get_speed();
  922. =cut
  923. sub get_speed {
  924. my ($self) = @_;
  925. my $res = { 'command' => 'getSpeed' };
  926. return $self->_execute_command($res);
  927. }
  928. =head2 set_speed
  929. Description:
  930. Set the user input speed.
  931. Input:
  932. STRING - One of these: SLOW, MEDIUM, FAST
  933. Usage:
  934. $driver->set_speed('MEDIUM');
  935. Note: This function is a no-op in WebDriver (?). See
  936. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  937. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  938. =cut
  939. sub set_speed {
  940. my ( $self, $speed ) = @_;
  941. if ( not defined $speed ) {
  942. return 'Speed not provided.';
  943. }
  944. my $res = { 'command' => 'setSpeed' };
  945. my $params = { 'speed' => $speed };
  946. return $self->_execute_command( $res, $params );
  947. }
  948. =head2 set_window_position
  949. Description:
  950. Set the position (on screen) where you want your browser to be displayed.
  951. Input:
  952. INT - x co-ordinate
  953. INT - y co-ordinate
  954. STRING - <optional> - window handle (default is 'current' window)
  955. Output:
  956. BOOLEAN - Success or failure
  957. Usage:
  958. $driver->set_window_position(50, 50);
  959. =cut
  960. sub set_window_position {
  961. my ( $self, $x, $y, $window ) = @_;
  962. $window = (defined $window)?$window:'current';
  963. if (not defined $x and not defined $y){
  964. croak "X & Y co-ordinates are required";
  965. }
  966. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  967. my $params = { 'x' => $x, 'y' => $y };
  968. my $ret = $self->_execute_command($res, $params);
  969. if ($ret =~ m/204/g) {
  970. return 1;
  971. }
  972. else { return 0; }
  973. }
  974. =head2 set_window_size
  975. Description:
  976. Set the size of the browser window
  977. Input:
  978. INT - height of the window
  979. INT - width of the window
  980. STRING - <optional> - window handle (default is 'current' window)
  981. Output:
  982. BOOLEAN - Success or failure
  983. Usage:
  984. $driver->set_window_size(640, 480);
  985. =cut
  986. sub set_window_size {
  987. my ( $self, $height, $width, $window ) = @_;
  988. $window = (defined $window)?$window:'current';
  989. if (not defined $height and not defined $width){
  990. croak "height & width of browser are required";
  991. }
  992. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  993. my $params = { 'height' => $height, 'width' => $width };
  994. my $ret = $self->_execute_command($res, $params);
  995. if ($ret =~ m/204/g) {
  996. return 1;
  997. }
  998. else { return 0; }
  999. }
  1000. =head2 get_all_cookies
  1001. Description:
  1002. Retrieve all cookies visible to the current page. Each cookie will be
  1003. returned as a HASH reference with the following keys & their value types:
  1004. 'name' - STRING
  1005. 'value' - STRING
  1006. 'path' - STRING
  1007. 'domain' - STRING
  1008. 'secure' - BOOLEAN
  1009. Output:
  1010. ARRAY of HASHES - list of all the cookie hashes
  1011. Usage:
  1012. print Dumper($driver->get_all_cookies());
  1013. =cut
  1014. sub get_all_cookies {
  1015. my ($self) = @_;
  1016. my $res = { 'command' => 'getAllCookies' };
  1017. return $self->_execute_command($res);
  1018. }
  1019. =head2 add_cookie
  1020. Description:
  1021. Set a cookie on the domain.
  1022. Input: 5 (1 optional)
  1023. Required:
  1024. 'name' - STRING
  1025. 'value' - STRING
  1026. 'path' - STRING
  1027. 'domain' - STRING
  1028. Optional:
  1029. 'secure' - BOOLEAN - default is false.
  1030. Usage:
  1031. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1032. =cut
  1033. sub add_cookie {
  1034. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1035. if ( ( not defined $name )
  1036. || ( not defined $value )
  1037. || ( not defined $path )
  1038. || ( not defined $domain ) )
  1039. {
  1040. croak "Missing parameters";
  1041. }
  1042. my $res = { 'command' => 'addCookie' };
  1043. my $json_false = JSON::false;
  1044. my $json_true = JSON::true;
  1045. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1046. my $params = {
  1047. 'cookie' => {
  1048. 'name' => $name,
  1049. 'value' => $value,
  1050. 'path' => $path,
  1051. 'domain' => $domain,
  1052. 'secure' => $secure,
  1053. }
  1054. };
  1055. return $self->_execute_command( $res, $params );
  1056. }
  1057. =head2 delete_all_cookies
  1058. Description:
  1059. Delete all cookies visible to the current page.
  1060. Usage:
  1061. $driver->delete_all_cookies();
  1062. =cut
  1063. sub delete_all_cookies {
  1064. my ($self) = @_;
  1065. my $res = { 'command' => 'deleteAllCookies' };
  1066. return $self->_execute_command($res);
  1067. }
  1068. =head2 delete_cookie_named
  1069. Description:
  1070. Delete the cookie with the given name. This command will be a no-op if there
  1071. is no such cookie visible to the current page.
  1072. Input: 1
  1073. Required:
  1074. STRING - name of cookie to delete
  1075. Usage:
  1076. $driver->delete_cookie_named('foo');
  1077. =cut
  1078. sub delete_cookie_named {
  1079. my ( $self, $cookie_name ) = @_;
  1080. if ( not defined $cookie_name ) {
  1081. croak "Cookie name not provided";
  1082. }
  1083. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1084. return $self->_execute_command($res);
  1085. }
  1086. =head2 get_page_source
  1087. Description:
  1088. Get the current page source.
  1089. Output:
  1090. STRING - The page source.
  1091. Usage:
  1092. print $driver->get_page_source();
  1093. =cut
  1094. sub get_page_source {
  1095. my ($self) = @_;
  1096. my $res = { 'command' => 'getPageSource' };
  1097. return $self->_execute_command($res);
  1098. }
  1099. =head2 find_element
  1100. Description:
  1101. Search for an element on the page, starting from the document root. The
  1102. located element will be returned as a WebElement object.
  1103. Input: 2 (1 optional)
  1104. Required:
  1105. STRING - The search target.
  1106. Optional:
  1107. STRING - Locator scheme to use to search the element, available schemes:
  1108. {class, class_name, css, id, link, link_text, partial_link_text,
  1109. tag_name, name, xpath}
  1110. Defaults to 'xpath'.
  1111. Output:
  1112. Selenium::Remote::WebElement - WebElement Object
  1113. Usage:
  1114. $driver->find_element("//input[\@name='q']");
  1115. =cut
  1116. sub find_element {
  1117. my ( $self, $query, $method ) = @_;
  1118. if ( not defined $query ) {
  1119. croak 'Search string to find element not provided.';
  1120. }
  1121. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  1122. if (defined $using) {
  1123. my $res = { 'command' => 'findElement' };
  1124. my $params = { 'using' => $using, 'value' => $query };
  1125. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1126. if($@) {
  1127. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1128. # give details on what element wasn't found
  1129. $@ = "$1: $query,$using";
  1130. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1131. croak $@;
  1132. } else {
  1133. # re throw if the exception wasn't what we expected
  1134. die $@;
  1135. }
  1136. }
  1137. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1138. }
  1139. else {
  1140. croak "Bad method, expected - class, class_name, css, id, link,
  1141. link_text, partial_link_text, name, tag_name, xpath";
  1142. }
  1143. }
  1144. =head2 find_elements
  1145. Description:
  1146. Search for multiple elements on the page, starting from the document root.
  1147. The located elements will be returned as an array of WebElement object.
  1148. Input: 2 (1 optional)
  1149. Required:
  1150. STRING - The search target.
  1151. Optional:
  1152. STRING - Locator scheme to use to search the element, available schemes:
  1153. {class, class_name, css, id, link, link_text, partial_link_text,
  1154. tag_name, name, xpath}
  1155. Defaults to 'xpath'.
  1156. Output:
  1157. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects
  1158. Usage:
  1159. $driver->find_elements("//input");
  1160. =cut
  1161. sub find_elements {
  1162. my ( $self, $query, $method ) = @_;
  1163. if ( not defined $query ) {
  1164. croak 'Search string to find element not provided.';
  1165. }
  1166. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  1167. if (defined $using) {
  1168. my $res = { 'command' => 'findElements' };
  1169. my $params = { 'using' => $using, 'value' => $query };
  1170. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1171. if($@) {
  1172. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1173. # give details on what element wasn't found
  1174. $@ = "$1: $query,$using";
  1175. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1176. croak $@;
  1177. } else {
  1178. # re throw if the exception wasn't what we expected
  1179. die $@;
  1180. }
  1181. }
  1182. my $elem_obj_arr;
  1183. my $i = 0;
  1184. foreach (@$ret_data) {
  1185. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  1186. $i++;
  1187. }
  1188. return wantarray?@{$elem_obj_arr}:$elem_obj_arr;
  1189. }
  1190. else {
  1191. croak "Bad method, expected - class, class_name, css, id, link,
  1192. link_text, partial_link_text, name, tag_name, xpath";
  1193. }
  1194. }
  1195. =head2 find_child_element
  1196. Description:
  1197. Search for an element on the page, starting from the identified element. The
  1198. located element will be returned as a WebElement object.
  1199. Input: 3 (1 optional)
  1200. Required:
  1201. Selenium::Remote::WebElement - WebElement object from where you want to
  1202. start searching.
  1203. STRING - The search target. (Do not use a double whack('//')
  1204. in an xpath to search for a child element
  1205. ex: '//option[@id="something"]'
  1206. instead use a dot whack ('./')
  1207. ex: './option[@id="something"]')
  1208. Optional:
  1209. STRING - Locator scheme to use to search the element, available schemes:
  1210. {class, class_name, css, id, link, link_text, partial_link_text,
  1211. tag_name, name, xpath}
  1212. Defaults to 'xpath'.
  1213. Output:
  1214. Selenium::Remote::WebElement - WebElement Object
  1215. Usage:
  1216. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1217. # note the usage of ./ when searching for a child element instead of //
  1218. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1219. =cut
  1220. sub find_child_element {
  1221. my ( $self, $elem, $query, $method ) = @_;
  1222. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1223. croak "Missing parameters";
  1224. }
  1225. my $using = ( defined $method ) ? $method : 'xpath';
  1226. if (exists FINDERS->{$using}) {
  1227. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1228. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1229. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1230. if($@) {
  1231. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1232. # give details on what element wasn't found
  1233. $@ = "$1: $query,$using";
  1234. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1235. croak $@;
  1236. } else {
  1237. # re throw if the exception wasn't what we expected
  1238. die $@;
  1239. }
  1240. }
  1241. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1242. }
  1243. else {
  1244. croak "Bad method, expected - class, class_name, css, id, link,
  1245. link_text, partial_link_text, name, tag_name, xpath";
  1246. }
  1247. }
  1248. =head2 find_child_elements
  1249. Description:
  1250. Search for multiple element on the page, starting from the identified
  1251. element. The located elements will be returned as an array of WebElement
  1252. objects.
  1253. Input: 3 (1 optional)
  1254. Required:
  1255. Selenium::Remote::WebElement - WebElement object from where you want to
  1256. start searching.
  1257. STRING - The search target.
  1258. Optional:
  1259. STRING - Locator scheme to use to search the element, available schemes:
  1260. {class, class_name, css, id, link, link_text, partial_link_text,
  1261. tag_name, name, xpath}
  1262. Defaults to 'xpath'.
  1263. Output:
  1264. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects.
  1265. Usage:
  1266. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1267. my $child = $driver->find_child_elements($elem1, "//option");
  1268. =cut
  1269. sub find_child_elements {
  1270. my ( $self, $elem, $query, $method ) = @_;
  1271. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1272. croak "Missing parameters";
  1273. }
  1274. my $using = ( defined $method ) ? $method : 'xpath';
  1275. if (exists FINDERS->{$using}) {
  1276. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1277. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1278. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1279. if($@) {
  1280. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1281. # give details on what element wasn't found
  1282. $@ = "$1: $query,$using";
  1283. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1284. croak $@;
  1285. } else {
  1286. # re throw if the exception wasn't what we expected
  1287. die $@;
  1288. }
  1289. }
  1290. my $elem_obj_arr;
  1291. my $i = 0;
  1292. foreach (@$ret_data) {
  1293. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  1294. $i++;
  1295. }
  1296. return wantarray?@{$elem_obj_arr}:$elem_obj_arr;
  1297. }
  1298. else {
  1299. croak "Bad method, expected - class, class_name, css, id, link,
  1300. link_text, partial_link_text, name, tag_name, xpath";
  1301. }
  1302. }
  1303. =head2 get_active_element
  1304. Description:
  1305. Get the element on the page that currently has focus.. The located element
  1306. will be returned as a WebElement object.
  1307. Output:
  1308. Selenium::Remote::WebElement - WebElement Object
  1309. Usage:
  1310. $driver->get_active_element();
  1311. =cut
  1312. sub get_active_element {
  1313. my ($self) = @_;
  1314. my $res = { 'command' => 'getActiveElement' };
  1315. my $ret_data = eval { $self->_execute_command($res) };
  1316. if ($@) {
  1317. croak $@;
  1318. } else {
  1319. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1320. }
  1321. }
  1322. =head2 send_modifier
  1323. Description:
  1324. Send an event to the active element to depress or release a modifier key.
  1325. Input: 2
  1326. Required:
  1327. 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
  1328. isdown - Boolean/String - Whether to generate a key down or key up
  1329. Usage:
  1330. $driver->send_modifier('Alt','down');
  1331. $elem->send_keys('c');
  1332. $driver->send_modifier('Alt','up');
  1333. or
  1334. $driver->send_modifier('Alt',1);
  1335. $elem->send_keys('c');
  1336. $driver->send_modifier('Alt',0);
  1337. =cut
  1338. sub send_modifier {
  1339. my ($self,$modifier,$isdown) = @_;
  1340. if($isdown =~ /(down|up)/) {
  1341. $isdown = $isdown =~ /down/ ? 1:0;
  1342. }
  1343. my $res = {'command' => 'sendModifier'};
  1344. my $params = {value => $modifier,
  1345. isdown => $isdown};
  1346. return $self->_execute_command($res,$params);
  1347. }
  1348. =head2 compare_elements
  1349. Description:
  1350. Test if two element IDs refer to the same DOM element.
  1351. Input: 2
  1352. Required:
  1353. Selenium::Remote::WebElement - WebElement Object
  1354. Selenium::Remote::WebElement - WebElement Object
  1355. Output:
  1356. BOOLEAN
  1357. Usage:
  1358. $driver->compare_elements($elem_obj1, $elem_obj2);
  1359. =cut
  1360. sub compare_elements {
  1361. my ($self, $elem1, $elem2) = @_;
  1362. my $res = { 'command' => 'elementEquals',
  1363. 'id' => $elem1->{id},
  1364. 'other' => $elem2->{id}
  1365. };
  1366. return $self->_execute_command($res);
  1367. }
  1368. =head2 click
  1369. Description:
  1370. Click any mouse button (at the coordinates set by the last moveto command).
  1371. Input:
  1372. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1373. defaults to 'LEFT'
  1374. Usage:
  1375. $driver->click('LEFT');
  1376. $driver->click(1); #MIDDLE
  1377. $driver->click('RIGHT');
  1378. $driver->click; #Defaults to left
  1379. =cut
  1380. sub click {
  1381. my ($self,$button) = @_;
  1382. my $button_enum = {LEFT=>0,MIDDLE=>1,RIGHT=>2};
  1383. if(defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i) {
  1384. $button = $button_enum->{uc $1};
  1385. } elsif(defined $button && $button =~ /(0|1|2)/) {
  1386. $button = $1;
  1387. } else {
  1388. $button = 0;
  1389. }
  1390. my $res = { 'command' => 'click' };
  1391. my $params = { 'button' => $button };
  1392. return $self->_execute_command($res,$button);
  1393. }
  1394. =head2 double_click
  1395. Description:
  1396. Double-clicks at the current mouse coordinates (set by moveto).
  1397. Usage:
  1398. $driver->double_click;
  1399. =cut
  1400. sub double_click {
  1401. my ($self) = @_;
  1402. my $res = { 'command' => 'doubleClick' };
  1403. return $self->_execute_command($res);
  1404. }
  1405. =head2 button_down
  1406. Description:
  1407. Click and hold the left mouse button (at the coordinates set by the
  1408. last moveto command). Note that the next mouse-related command that
  1409. should follow is buttondown . Any other mouse command (such as click
  1410. or another call to buttondown) will yield undefined behaviour.
  1411. Usage:
  1412. $self->button_down;
  1413. =cut
  1414. sub button_down {
  1415. my ($self) = @_;
  1416. my $res = { 'command' => 'buttonDown' };
  1417. return $self->_execute_command($res);
  1418. }
  1419. =head2 button_up
  1420. Description:
  1421. Releases the mouse button previously held (where the mouse is
  1422. currently at). Must be called once for every buttondown command
  1423. issued. See the note in click and buttondown about implications of
  1424. out-of-order commands.
  1425. Usage:
  1426. $self->button_up;
  1427. =cut
  1428. sub button_up {
  1429. my ($self) = @_;
  1430. my $res = { 'command' => 'buttonUp' };
  1431. return $self->_execute_command($res);
  1432. }
  1433. =head2 upload_file
  1434. Description:
  1435. Upload a file from the local machine to the selenium server
  1436. machine. That file then can be used for testing file upload on web
  1437. forms. Returns the remote-server's path to the file.
  1438. Usage:
  1439. my $remote_fname = $driver->upload_file( $fname );
  1440. my $element = $driver->find_element( '//input[@id="file"]' );
  1441. $element->send_keys( $remote_fname );
  1442. =cut
  1443. # this method duplicates upload() method in the
  1444. # org.openqa.selenium.remote.RemoteWebElement java class.
  1445. sub upload_file {
  1446. my ($self, $filename) = @_;
  1447. if (not -r $filename) { die "upload_file: no such file: $filename"; }
  1448. my $string = ""; # buffer
  1449. zip $filename => \$string
  1450. or die "zip failed: $ZipError\n"; # compress the file into string
  1451. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  1452. my $params = {
  1453. file => encode_base64($string) # base64-encoded string
  1454. };
  1455. return $self->_execute_command($res, $params);
  1456. }
  1457. 1;
  1458. __END__
  1459. =head1 SEE ALSO
  1460. For more information about Selenium , visit the website at
  1461. L<http://code.google.com/p/selenium/>.
  1462. Also checkout project's wiki page at
  1463. L<https://github.com/aivaturi/Selenium-Remote-Driver/wiki>.
  1464. =head1 BUGS
  1465. The Selenium issue tracking system is available online at
  1466. L<http://github.com/aivaturi/Selenium-Remote-Driver/issues>.
  1467. =head1 AUTHOR
  1468. Perl Bindings for Selenium Remote Driver by Aditya Ivaturi C<< <ivaturi@gmail.com> >>
  1469. =head1 ACKNOWLEDGEMENTS
  1470. The following people have contributed to this module. (Thanks!)
  1471. =over 4
  1472. =item * Gordon Child
  1473. =item * Phil Kania
  1474. =item * Phil Mitchell
  1475. =item * Allen Lew
  1476. =item * Tom Hukins
  1477. =back
  1478. =head1 LICENSE
  1479. Copyright (c) 2010-2011 Aditya Ivaturi, Gordon Child
  1480. Licensed under the Apache License, Version 2.0 (the "License");
  1481. you may not use this file except in compliance with the License.
  1482. You may obtain a copy of the License at
  1483. http://www.apache.org/licenses/LICENSE-2.0
  1484. Unless required by applicable law or agreed to in writing, software
  1485. distributed under the License is distributed on an "AS IS" BASIS,
  1486. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1487. See the License for the specific language governing permissions and
  1488. limitations under the License.