Driver.pm 52 KB

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