1
0

Driver.pm 55 KB

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