1
0

Driver.pm 51 KB

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