Driver.pm 55 KB

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