1
0

Driver.pm 52 KB

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