Driver.pm 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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 get_sessions
  258. Description:
  259. Returns a list of the currently active sessions. Each session will be
  260. returned as an array of Hashes with the following keys:
  261. 'id' : The session ID
  262. 'capabilities: An object describing session's capabilities
  263. Output:
  264. Array of Hashes
  265. Usage:
  266. print Dumper $driver->get_sessions();
  267. =cut
  268. sub get_sessions{
  269. my ($self) = @_;
  270. my $res = { 'command' => 'getSessions' };
  271. return $self->_execute_command($res);
  272. }
  273. =head2 status
  274. Description:
  275. Query the server's current status. All server implementations
  276. should return two basic objects describing the server's current
  277. platform and when the server was built.
  278. Output:
  279. Hash ref
  280. Usage:
  281. print Dumper $driver->status;
  282. =cut
  283. sub status {
  284. my ($self) = @_;
  285. my $res = { 'command' => 'status' };
  286. return $self->_execute_command($res);
  287. }
  288. =head2 get_alert_text
  289. Description:
  290. Gets the text of the currently displayed JavaScript alert(), confirm()
  291. or prompt() dialog.
  292. Example
  293. my $string = $driver->get_alert_text;
  294. =cut
  295. sub get_alert_text {
  296. my ($self) = @_;
  297. my $res = { 'command' => 'getAlertText' };
  298. return $self->_execute_command($res);
  299. }
  300. =head2 send_keys_to_active_element
  301. Description:
  302. Send a sequence of key strokes to the active element. This command is
  303. similar to the send keys command in every aspect except the implicit
  304. termination: The modifiers are not released at the end of the call.
  305. Rather, the state of the modifier keys is kept between calls, so mouse
  306. interactions can be performed while modifier keys are depressed.
  307. Input: 1
  308. Required:
  309. {ARRAY | STRING} - Array of strings or a string.
  310. Usage:
  311. $driver->send_keys_to_active_element('abcd', 'efg');
  312. $driver->send_keys_to_active_element('hijk');
  313. or
  314. # include the WDKeys module
  315. use Selenium::Remote::WDKeys;
  316. .
  317. .
  318. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  319. =cut
  320. sub send_keys_to_active_element {
  321. my ($self, @strings) = @_;
  322. my $res = { 'command' => 'sendKeysToActiveElement' };
  323. my $params = {
  324. 'value' => \@strings,
  325. };
  326. return $self->_execute_command($res, $params);
  327. }
  328. =head2 send_keys_to_alert
  329. Synonymous with send_keys_to_prompt
  330. =cut
  331. sub send_keys_to_alert {
  332. return shift->send_keys_to_prompt(@_);
  333. }
  334. =head2 send_keys_to_prompt
  335. Description:
  336. Sends keystrokes to a JavaScript prompt() dialog.
  337. Input:
  338. {string} keys to send
  339. Example:
  340. $driver->send_keys_to_prompt('hello world');
  341. or
  342. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  343. $driver->send_keys_to_alert("Larry Wall");
  344. $driver->accept_alert;
  345. =cut
  346. sub send_keys_to_prompt {
  347. my ($self,$keys) = @_;
  348. my $res = { 'command' => 'sendKeysToPrompt' };
  349. my $params = { 'text' => $keys };
  350. return $self->_execute_command($res,$params);
  351. }
  352. =head2 accept_alert
  353. Description:
  354. Accepts the currently displayed alert dialog. Usually, this is
  355. equivalent to clicking the 'OK' button in the dialog.
  356. Example:
  357. $driver->accept_alert;
  358. =cut
  359. sub accept_alert {
  360. my ($self) = @_;
  361. my $res = { 'command' => 'acceptAlert' };
  362. return $self->_execute_command($res);
  363. }
  364. =head2 dismiss_alert
  365. Description:
  366. Dismisses the currently displayed alert dialog. For comfirm()
  367. and prompt() dialogs, this is equivalent to clicking the
  368. 'Cancel' button. For alert() dialogs, this is equivalent to
  369. clicking the 'OK' button.
  370. Example:
  371. $driver->dismiss_alert;
  372. =cut
  373. sub dismiss_alert {
  374. my ($self) = @_;
  375. my $res = { 'command' => 'dismissAlert' };
  376. return $self->_execute_command($res);
  377. }
  378. =head2 mouse_move_to_location
  379. Description:
  380. Move the mouse by an offset of the specificed element. If no
  381. element is specified, the move is relative to the current mouse
  382. cursor. If an element is provided but no offset, the mouse will be
  383. moved to the center of the element. If the element is not visible,
  384. it will be scrolled into view.
  385. Output:
  386. STRING -
  387. Usage:
  388. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  389. # 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.
  390. # 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.
  391. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  392. =cut
  393. sub mouse_move_to_location {
  394. my ($self, %params) = @_;
  395. $params{element} = $params{element}{id} if exists $params{element};
  396. my $res = { 'command' => 'mouseMoveToLocation' };
  397. return $self->_execute_command($res, \%params);
  398. }
  399. =head2 move_to
  400. Synonymous with mouse_move_to_location
  401. =cut
  402. sub move_to {
  403. return shift->mouse_move_to_location(@_);
  404. }
  405. =head2 get_capabilities
  406. Description:
  407. Retrieve the capabilities of the specified session.
  408. Output:
  409. HASH of all the capabilities.
  410. Usage:
  411. my $capab = $driver->get_capabilities();
  412. print Dumper($capab);
  413. =cut
  414. sub get_capabilities {
  415. my $self = shift;
  416. my $res = {'command' => 'getCapabilities'};
  417. return $self->_execute_command($res);
  418. }
  419. =head2 set_async_script_timeout
  420. Description:
  421. Set the amount of time, in milliseconds, that asynchronous scripts executed
  422. by execute_async_script() are permitted to run before they are
  423. aborted and a |Timeout| error is returned to the client.
  424. Input:
  425. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  426. commands are permitted to run.
  427. Usage:
  428. $driver->set_async_script_timeout(1000);
  429. =cut
  430. sub set_async_script_timeout {
  431. my ($self, $ms) = @_;
  432. if (not defined $ms)
  433. {
  434. return "Expecting timeout in ms";
  435. }
  436. my $res = {'command' => 'setAsyncScriptTimeout'};
  437. my $params = {'ms' => $ms};
  438. return $self->_execute_command($res, $params);
  439. }
  440. =head2 set_implicit_wait_timeout
  441. Description:
  442. Set the amount of time the driver should wait when searching for elements.
  443. When searching for a single element, the driver will poll the page until
  444. an element is found or the timeout expires, whichever occurs first.
  445. When searching for multiple elements, the driver should poll the page until
  446. at least one element is found or the timeout expires, at which point it
  447. will return an empty list. If this method is never called, the driver will
  448. default to an implicit wait of 0ms.
  449. Input:
  450. Time in milliseconds.
  451. Output:
  452. Server Response Hash with no data returned back from the server.
  453. Usage:
  454. $driver->set_implicit_wait_timeout(10);
  455. =cut
  456. sub set_implicit_wait_timeout {
  457. my ($self, $ms) = @_;
  458. my $res = {'command' => 'setImplicitWaitTimeout'};
  459. my $params = {'ms' => $ms};
  460. return $self->_execute_command($res, $params);
  461. }
  462. =head2 close
  463. Description:
  464. Close the current window.
  465. Usage:
  466. $driver->close();
  467. or
  468. #close a popup window
  469. my $handles = $driver->get_window_handles;
  470. $driver->switch_to_window($handles->[1]);
  471. $driver->close();
  472. $driver->switch_to_window($handles->[0]);
  473. =cut
  474. sub close {
  475. my $self = shift;
  476. my $res = { 'command' => 'close' };
  477. $self->_execute_command($res);
  478. }
  479. =head2 quit
  480. Description:
  481. Delete the session & close open browsers.
  482. Usage:
  483. $driver->quit();
  484. =cut
  485. sub quit {
  486. my $self = shift;
  487. my $res = { 'command' => 'quit' };
  488. $self->_execute_command($res);
  489. $self->{session_id} = undef;
  490. }
  491. =head2 get_current_window_handle
  492. Description:
  493. Retrieve the current window handle.
  494. Output:
  495. STRING - the window handle
  496. Usage:
  497. print $driver->get_current_window_handle();
  498. =cut
  499. sub get_current_window_handle {
  500. my $self = shift;
  501. my $res = { 'command' => 'getCurrentWindowHandle' };
  502. return $self->_execute_command($res);
  503. }
  504. =head2 get_window_handles
  505. Description:
  506. Retrieve the list of window handles used in the session.
  507. Output:
  508. ARRAY of STRING - list of the window handles
  509. Usage:
  510. print Dumper $driver->get_window_handles;
  511. or
  512. # get popup, close, then back
  513. my $handles = $driver->get_window_handles;
  514. $driver->switch_to_window($handles->[1]);
  515. $driver->close;
  516. $driver->switch_to_window($handles->[0]);
  517. =cut
  518. sub get_window_handles {
  519. my $self = shift;
  520. my $res = { 'command' => 'getWindowHandles' };
  521. return $self->_execute_command($res);
  522. }
  523. =head2 get_window_size
  524. Description:
  525. Retrieve the window size
  526. Input:
  527. STRING - <optional> - window handle (default is 'current' window)
  528. Output:
  529. HASH - containing keys 'height' & 'width'
  530. Usage:
  531. my $window_size = $driver->get_window_size();
  532. print $window_size->{'height'}, $window_size->('width');
  533. =cut
  534. sub get_window_size {
  535. my ( $self, $window ) = @_;
  536. $window = (defined $window)?$window:'current';
  537. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  538. return $self->_execute_command($res);
  539. }
  540. =head2 get_window_position
  541. Description:
  542. Retrieve the window position
  543. Input:
  544. STRING - <optional> - window handle (default is 'current' window)
  545. Output:
  546. HASH - containing keys 'x' & 'y'
  547. Usage:
  548. my $window_size = $driver->get_window_position();
  549. print $window_size->{'x'}, $window_size->('y');
  550. =cut
  551. sub get_window_position {
  552. my ( $self, $window ) = @_;
  553. $window = (defined $window)?$window:'current';
  554. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  555. return $self->_execute_command($res);
  556. }
  557. =head2 get_current_url
  558. Description:
  559. Retrieve the url of the current page
  560. Output:
  561. STRING - url
  562. Usage:
  563. print $driver->get_current_url();
  564. =cut
  565. sub get_current_url {
  566. my $self = shift;
  567. my $res = { 'command' => 'getCurrentUrl' };
  568. return $self->_execute_command($res);
  569. }
  570. =head2 navigate
  571. Description:
  572. Navigate to a given url. This is same as get() method.
  573. Input:
  574. STRING - url
  575. Usage:
  576. $driver->navigate('http://www.google.com');
  577. =cut
  578. sub navigate {
  579. my ( $self, $url ) = @_;
  580. $self->get($url);
  581. }
  582. =head2 get
  583. Description:
  584. Navigate to a given url
  585. Input:
  586. STRING - url
  587. Usage:
  588. $driver->get('http://www.google.com');
  589. =cut
  590. sub get {
  591. my ( $self, $url ) = @_;
  592. my $res = { 'command' => 'get' };
  593. my $params = { 'url' => $url };
  594. return $self->_execute_command( $res, $params );
  595. }
  596. =head2 get_title
  597. Description:
  598. Get the current page title
  599. Output:
  600. STRING - Page title
  601. Usage:
  602. print $driver->get_title();
  603. =cut
  604. sub get_title {
  605. my $self = shift;
  606. my $res = { 'command' => 'getTitle' };
  607. return $self->_execute_command($res);
  608. }
  609. =head2 go_back
  610. Description:
  611. Equivalent to hitting the back button on the browser.
  612. Usage:
  613. $driver->go_back();
  614. =cut
  615. sub go_back {
  616. my $self = shift;
  617. my $res = { 'command' => 'goBack' };
  618. return $self->_execute_command($res);
  619. }
  620. =head2 go_forward
  621. Description:
  622. Equivalent to hitting the forward button on the browser.
  623. Usage:
  624. $driver->go_forward();
  625. =cut
  626. sub go_forward {
  627. my $self = shift;
  628. my $res = { 'command' => 'goForward' };
  629. return $self->_execute_command($res);
  630. }
  631. =head2 refresh
  632. Description:
  633. Reload the current page.
  634. Usage:
  635. $driver->refresh();
  636. =cut
  637. sub refresh {
  638. my $self = shift;
  639. my $res = { 'command' => 'refresh' };
  640. return $self->_execute_command($res);
  641. }
  642. =head2 javascript
  643. Description:
  644. returns true if javascript is enabled in the driver.
  645. Usage:
  646. if ($driver->javascript) { ...; }
  647. =cut
  648. sub javascript {
  649. my $self = shift;
  650. return $self->{javascript} == JSON::true;
  651. }
  652. =head2 execute_async_script
  653. Description:
  654. Inject a snippet of JavaScript into the page for execution in the context
  655. of the currently selected frame. The executed script is assumed to be
  656. asynchronous and must signal that is done by invoking the provided
  657. callback, which is always provided as the final argument to the function.
  658. The value to this callback will be returned to the client.
  659. Asynchronous script commands may not span page loads. If an unload event
  660. is fired while waiting for a script result, an error should be returned
  661. to the client.
  662. Input: 2 (1 optional)
  663. Required:
  664. STRING - Javascript to execute on the page
  665. Optional:
  666. ARRAY - list of arguments that need to be passed to the script.
  667. Output:
  668. {*} - Varied, depending on the type of result expected back from the script.
  669. Usage:
  670. my $script = q{
  671. var arg1 = arguments[0];
  672. var callback = arguments[arguments.length-1];
  673. var elem = window.document.findElementById(arg1);
  674. callback(elem);
  675. };
  676. my $callback = q{return arguments[0];};
  677. my $elem = $driver->execute_async_script($script,'myid',$callback);
  678. $elem->click;
  679. =cut
  680. sub execute_async_script {
  681. my ( $self, $script, @args ) = @_;
  682. if ($self->javascript) {
  683. if ( not defined $script ) {
  684. return 'No script provided';
  685. }
  686. my $res = { 'command' => 'executeAsyncScript' };
  687. # Check the args array if the elem obj is provided & replace it with
  688. # JSON representation
  689. for (my $i=0; $i<@args; $i++) {
  690. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  691. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  692. }
  693. }
  694. my $params = {'script' => $script, 'args' => \@args};
  695. my $ret = $self->_execute_command($res, $params);
  696. # replace any ELEMENTS with WebElement
  697. if (ref($ret) and (ref($ret) eq 'HASH') and exists $ret->{'ELEMENT'}) {
  698. $ret =
  699. new Selenium::Remote::WebElement(
  700. $ret->{ELEMENT}, $self);
  701. }
  702. return $ret;
  703. }
  704. else {
  705. croak 'Javascript is not enabled on remote driver instance.';
  706. }
  707. }
  708. =head2 execute_script
  709. Description:
  710. Inject a snippet of JavaScript into the page and return its result.
  711. WebElements that should be passed to the script as an argument should be
  712. specified in the arguments array as WebElement object. Likewise,
  713. any WebElements in the script result will be returned as WebElement object.
  714. Input: 2 (1 optional)
  715. Required:
  716. STRING - Javascript to execute on the page
  717. Optional:
  718. ARRAY - list of arguments that need to be passed to the script.
  719. Output:
  720. {*} - Varied, depending on the type of result expected back from the script.
  721. Usage:
  722. my $script = q{
  723. var arg1 = arguments[0];
  724. var elem = window.document.findElementById(arg1);
  725. return elem;
  726. };
  727. my $elem = $driver->execute_script($script,'myid');
  728. $elem->click;
  729. =cut
  730. sub execute_script {
  731. my ( $self, $script, @args ) = @_;
  732. if ($self->javascript) {
  733. if ( not defined $script ) {
  734. return 'No script provided';
  735. }
  736. my $res = { 'command' => 'executeScript' };
  737. # Check the args array if the elem obj is provided & replace it with
  738. # JSON representation
  739. for (my $i=0; $i<@args; $i++) {
  740. if (ref $args[$i] eq 'Selenium::Remote::WebElement') {
  741. $args[$i] = {'ELEMENT' => ($args[$i])->{id}};
  742. }
  743. }
  744. my $params = {'script' => $script, 'args' => [@args]};
  745. my $ret = $self->_execute_command($res, $params);
  746. return $self->_convert_to_webelement($ret);
  747. }
  748. else {
  749. croak 'Javascript is not enabled on remote driver instance.';
  750. }
  751. }
  752. # _convert_to_webelement
  753. # An internal method used to traverse a data structure
  754. # and convert any ELEMENTS with WebElements
  755. sub _convert_to_webelement {
  756. my ($self, $ret ) = @_;
  757. if (ref($ret) and (ref($ret) eq 'HASH')) {
  758. if((keys %$ret==1) and exists $ret->{'ELEMENT'}) {
  759. # replace an ELEMENT with WebElement
  760. return new Selenium::Remote::WebElement($ret->{ELEMENT}, $self);
  761. }
  762. my %hash;
  763. foreach my $key (keys %$ret) {
  764. $hash{$key}=$self->_convert_to_webelement($ret->{$key});
  765. }
  766. return \%hash;
  767. }
  768. if(ref($ret) and (ref($ret) eq 'ARRAY')) {
  769. my @array = map {$self->_convert_to_webelement($_)} @$ret;
  770. return \@array;
  771. }
  772. return $ret;
  773. }
  774. =head2 screenshot
  775. Description:
  776. Get a screenshot of the current page as a base64 encoded image.
  777. Output:
  778. STRING - base64 encoded image
  779. Usage:
  780. print $driver->screenshot();
  781. or
  782. require MIME::Base64;
  783. open(FH,'>','screenshot.png');
  784. binmode FH;
  785. my $png_base64 = $driver->screenshot();
  786. print FH MIME::Base64::decode_base64($png_base64);
  787. close FH;
  788. =cut
  789. sub screenshot {
  790. my ($self) = @_;
  791. my $res = { 'command' => 'screenshot' };
  792. return $self->_execute_command($res);
  793. }
  794. =head2 available_engines
  795. Description:
  796. List all available engines on the machine. To use an engine, it has to be present in this list.
  797. Output:
  798. {Array.<string>} A list of available engines
  799. Usage:
  800. print Dumper $driver->available_engines;
  801. =cut
  802. sub available_engines {
  803. my ($self) = @_;
  804. my $res = { 'command' => 'availableEngines' };
  805. return $self->_execute_command($res);
  806. }
  807. =head2 switch_to_frame
  808. Description:
  809. Change focus to another frame on the page. If the frame ID is null, the
  810. server will switch to the page's default content.
  811. Input: 1
  812. Required:
  813. {STRING | NUMBER | NULL} - ID of the frame which can be one of the three
  814. mentioned.
  815. Usage:
  816. $driver->switch_to_frame('frame_1');
  817. =cut
  818. sub switch_to_frame {
  819. my ( $self, $id ) = @_;
  820. my $json_null = JSON::null;
  821. $id = ( defined $id ) ? $id : $json_null;
  822. my $res = { 'command' => 'switchToFrame' };
  823. my $params = { 'id' => $id };
  824. return $self->_execute_command( $res, $params );
  825. }
  826. =head2 switch_to_window
  827. Description:
  828. Change focus to another window. The window to change focus to may be
  829. specified by its server assigned window handle, or by the value of its name
  830. attribute.
  831. Input: 1
  832. Required:
  833. STRING - Window handle or the Window name
  834. Usage:
  835. $driver->switch_to_window('MY Homepage');
  836. or
  837. # close a popup window and switch back
  838. my $handles = $driver->get_window_handles;
  839. $driver->switch_to_window($handles->[1]);
  840. $driver->close;
  841. $driver->switch_to_window($handles->[0]);
  842. =cut
  843. sub switch_to_window {
  844. my ( $self, $name ) = @_;
  845. if ( not defined $name ) {
  846. return 'Window name not provided';
  847. }
  848. my $res = { 'command' => 'switchToWindow' };
  849. my $params = { 'name' => $name };
  850. return $self->_execute_command( $res, $params );
  851. }
  852. =head2 get_speed
  853. Description:
  854. Get the current user input speed. The actual input speed is still browser
  855. specific and not covered by the Driver.
  856. Output:
  857. STRING - One of these: SLOW, MEDIUM, FAST
  858. Usage:
  859. print $driver->get_speed();
  860. =cut
  861. sub get_speed {
  862. my ($self) = @_;
  863. my $res = { 'command' => 'getSpeed' };
  864. return $self->_execute_command($res);
  865. }
  866. =head2 set_speed
  867. Description:
  868. Set the user input speed.
  869. Input:
  870. STRING - One of these: SLOW, MEDIUM, FAST
  871. Usage:
  872. $driver->set_speed('MEDIUM');
  873. Note: This function is a no-op in WebDriver (?). See
  874. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  875. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  876. =cut
  877. sub set_speed {
  878. my ( $self, $speed ) = @_;
  879. if ( not defined $speed ) {
  880. return 'Speed not provided.';
  881. }
  882. my $res = { 'command' => 'setSpeed' };
  883. my $params = { 'speed' => $speed };
  884. return $self->_execute_command( $res, $params );
  885. }
  886. =head2 set_window_position
  887. Description:
  888. Set the position (on screen) where you want your browser to be displayed.
  889. Input:
  890. INT - x co-ordinate
  891. INT - y co-ordinate
  892. STRING - <optional> - window handle (default is 'current' window)
  893. Output:
  894. BOOLEAN - Success or failure
  895. Usage:
  896. $driver->set_window_position(50, 50);
  897. =cut
  898. sub set_window_position {
  899. my ( $self, $x, $y, $window ) = @_;
  900. $window = (defined $window)?$window:'current';
  901. if (not defined $x and not defined $y){
  902. return "X & Y co-ordinates are required";
  903. }
  904. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  905. my $params = { 'x' => $x, 'y' => $y };
  906. my $ret = $self->_execute_command($res, $params);
  907. if ($ret =~ m/204/g) {
  908. return 1;
  909. }
  910. else { return 0; }
  911. }
  912. =head2 set_window_size
  913. Description:
  914. Set the size of the browser window
  915. Input:
  916. INT - height of the window
  917. INT - width of the window
  918. STRING - <optional> - window handle (default is 'current' window)
  919. Output:
  920. BOOLEAN - Success or failure
  921. Usage:
  922. $driver->set_window_size(640, 480);
  923. =cut
  924. sub set_window_size {
  925. my ( $self, $height, $width, $window ) = @_;
  926. $window = (defined $window)?$window:'current';
  927. if (not defined $height and not defined $width){
  928. return "height & width of browser are required";
  929. }
  930. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  931. my $params = { 'height' => $height, 'width' => $width };
  932. my $ret = $self->_execute_command($res, $params);
  933. if ($ret =~ m/204/g) {
  934. return 1;
  935. }
  936. else { return 0; }
  937. }
  938. =head2 get_all_cookies
  939. Description:
  940. Retrieve all cookies visible to the current page. Each cookie will be
  941. returned as a HASH reference with the following keys & their value types:
  942. 'name' - STRING
  943. 'value' - STRING
  944. 'path' - STRING
  945. 'domain' - STRING
  946. 'secure' - BOOLEAN
  947. Output:
  948. ARRAY of HASHES - list of all the cookie hashes
  949. Usage:
  950. print Dumper($driver->get_all_cookies());
  951. =cut
  952. sub get_all_cookies {
  953. my ($self) = @_;
  954. my $res = { 'command' => 'getAllCookies' };
  955. return $self->_execute_command($res);
  956. }
  957. =head2 add_cookie
  958. Description:
  959. Set a cookie on the domain.
  960. Input: 5 (1 optional)
  961. Required:
  962. 'name' - STRING
  963. 'value' - STRING
  964. 'path' - STRING
  965. 'domain' - STRING
  966. Optional:
  967. 'secure' - BOOLEAN - default is false.
  968. Usage:
  969. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  970. =cut
  971. sub add_cookie {
  972. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  973. if ( ( not defined $name )
  974. || ( not defined $value )
  975. || ( not defined $path )
  976. || ( not defined $domain ) )
  977. {
  978. return "Missing parameters";
  979. }
  980. my $res = { 'command' => 'addCookie' };
  981. my $json_false = JSON::false;
  982. my $json_true = JSON::true;
  983. $secure = ( defined $secure ) ? $json_true : $json_false;
  984. my $params = {
  985. 'cookie' => {
  986. 'name' => $name,
  987. 'value' => $value,
  988. 'path' => $path,
  989. 'domain' => $domain,
  990. 'secure' => $secure,
  991. }
  992. };
  993. return $self->_execute_command( $res, $params );
  994. }
  995. =head2 delete_all_cookies
  996. Description:
  997. Delete all cookies visible to the current page.
  998. Usage:
  999. $driver->delete_all_cookies();
  1000. =cut
  1001. sub delete_all_cookies {
  1002. my ($self) = @_;
  1003. my $res = { 'command' => 'deleteAllCookies' };
  1004. return $self->_execute_command($res);
  1005. }
  1006. =head2 delete_cookie_named
  1007. Description:
  1008. Delete the cookie with the given name. This command will be a no-op if there
  1009. is no such cookie visible to the current page.
  1010. Input: 1
  1011. Required:
  1012. STRING - name of cookie to delete
  1013. Usage:
  1014. $driver->delete_cookie_named('foo');
  1015. =cut
  1016. sub delete_cookie_named {
  1017. my ( $self, $cookie_name ) = @_;
  1018. if ( not defined $cookie_name ) {
  1019. return "Cookie name not provided";
  1020. }
  1021. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1022. return $self->_execute_command($res);
  1023. }
  1024. =head2 get_page_source
  1025. Description:
  1026. Get the current page source.
  1027. Output:
  1028. STRING - The page source.
  1029. Usage:
  1030. print $driver->get_page_source();
  1031. =cut
  1032. sub get_page_source {
  1033. my ($self) = @_;
  1034. my $res = { 'command' => 'getPageSource' };
  1035. return $self->_execute_command($res);
  1036. }
  1037. =head2 find_element
  1038. Description:
  1039. Search for an element on the page, starting from the document root. The
  1040. located element will be returned as a WebElement object.
  1041. Input: 2 (1 optional)
  1042. Required:
  1043. STRING - The search target.
  1044. Optional:
  1045. STRING - Locator scheme to use to search the element, available schemes:
  1046. {class, class_name, css, id, link, link_text, partial_link_text,
  1047. tag_name, name, xpath}
  1048. Defaults to 'xpath'.
  1049. Output:
  1050. Selenium::Remote::WebElement - WebElement Object
  1051. Usage:
  1052. $driver->find_element("//input[\@name='q']");
  1053. =cut
  1054. sub find_element {
  1055. my ( $self, $query, $method ) = @_;
  1056. if ( not defined $query ) {
  1057. return 'Search string to find element not provided.';
  1058. }
  1059. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  1060. if (defined $using) {
  1061. my $res = { 'command' => 'findElement' };
  1062. my $params = { 'using' => $using, 'value' => $query };
  1063. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1064. if($@) {
  1065. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1066. # give details on what element wasn't found
  1067. $@ = "$1: $query,$using";
  1068. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1069. croak $@;
  1070. } else {
  1071. # re throw if the exception wasn't what we expected
  1072. die $@;
  1073. }
  1074. }
  1075. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1076. }
  1077. else {
  1078. croak "Bad method, expected - class, class_name, css, id, link,
  1079. link_text, partial_link_text, name, tag_name, xpath";
  1080. }
  1081. }
  1082. =head2 find_elements
  1083. Description:
  1084. Search for multiple elements on the page, starting from the document root.
  1085. The located elements will be returned as an array of WebElement object.
  1086. Input: 2 (1 optional)
  1087. Required:
  1088. STRING - The search target.
  1089. Optional:
  1090. STRING - Locator scheme to use to search the element, available schemes:
  1091. {class, class_name, css, id, link, link_text, partial_link_text,
  1092. tag_name, name, xpath}
  1093. Defaults to 'xpath'.
  1094. Output:
  1095. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects
  1096. Usage:
  1097. $driver->find_elements("//input");
  1098. =cut
  1099. sub find_elements {
  1100. my ( $self, $query, $method ) = @_;
  1101. if ( not defined $query ) {
  1102. return 'Search string to find element not provided.';
  1103. }
  1104. my $using = ( defined $method ) ? FINDERS->{$method} : 'xpath';
  1105. if (defined $using) {
  1106. my $res = { 'command' => 'findElements' };
  1107. my $params = { 'using' => $using, 'value' => $query };
  1108. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1109. if($@) {
  1110. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1111. # give details on what element wasn't found
  1112. $@ = "$1: $query,$using";
  1113. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1114. croak $@;
  1115. } else {
  1116. # re throw if the exception wasn't what we expected
  1117. die $@;
  1118. }
  1119. }
  1120. my $elem_obj_arr;
  1121. my $i = 0;
  1122. foreach (@$ret_data) {
  1123. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  1124. $i++;
  1125. }
  1126. return wantarray?@{$elem_obj_arr}:$elem_obj_arr;
  1127. }
  1128. else {
  1129. croak "Bad method, expected - class, class_name, css, id, link,
  1130. link_text, partial_link_text, name, tag_name, xpath";
  1131. }
  1132. }
  1133. =head2 find_child_element
  1134. Description:
  1135. Search for an element on the page, starting from the identified element. The
  1136. located element will be returned as a WebElement object.
  1137. Input: 3 (1 optional)
  1138. Required:
  1139. Selenium::Remote::WebElement - WebElement object from where you want to
  1140. start searching.
  1141. STRING - The search target. (Do not use a double whack('//')
  1142. in an xpath to search for a child element
  1143. ex: '//option[@id="something"]'
  1144. instead use a dot whack ('./')
  1145. ex: './option[@id="something"]')
  1146. Optional:
  1147. STRING - Locator scheme to use to search the element, available schemes:
  1148. {class, class_name, css, id, link, link_text, partial_link_text,
  1149. tag_name, name, xpath}
  1150. Defaults to 'xpath'.
  1151. Output:
  1152. Selenium::Remote::WebElement - WebElement Object
  1153. Usage:
  1154. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1155. # note the usage of ./ when searching for a child element instead of //
  1156. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1157. =cut
  1158. sub find_child_element {
  1159. my ( $self, $elem, $query, $method ) = @_;
  1160. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1161. return "Missing parameters";
  1162. }
  1163. my $using = ( defined $method ) ? $method : 'xpath';
  1164. if (exists FINDERS->{$using}) {
  1165. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1166. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1167. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1168. if($@) {
  1169. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1170. # give details on what element wasn't found
  1171. $@ = "$1: $query,$using";
  1172. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1173. croak $@;
  1174. } else {
  1175. # re throw if the exception wasn't what we expected
  1176. die $@;
  1177. }
  1178. }
  1179. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1180. }
  1181. else {
  1182. croak "Bad method, expected - class, class_name, css, id, link,
  1183. link_text, partial_link_text, name, tag_name, xpath";
  1184. }
  1185. }
  1186. =head2 find_child_elements
  1187. Description:
  1188. Search for multiple element on the page, starting from the identified
  1189. element. The located elements will be returned as an array of WebElement
  1190. objects.
  1191. Input: 3 (1 optional)
  1192. Required:
  1193. Selenium::Remote::WebElement - WebElement object from where you want to
  1194. start searching.
  1195. STRING - The search target.
  1196. Optional:
  1197. STRING - Locator scheme to use to search the element, available schemes:
  1198. {class, class_name, css, id, link, link_text, partial_link_text,
  1199. tag_name, name, xpath}
  1200. Defaults to 'xpath'.
  1201. Output:
  1202. ARRAY of Selenium::Remote::WebElement - Array of WebElement Objects.
  1203. Usage:
  1204. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1205. my $child = $driver->find_child_elements($elem1, "//option");
  1206. =cut
  1207. sub find_child_elements {
  1208. my ( $self, $elem, $query, $method ) = @_;
  1209. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1210. return "Missing parameters";
  1211. }
  1212. my $using = ( defined $method ) ? $method : 'xpath';
  1213. if (exists FINDERS->{$using}) {
  1214. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1215. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1216. my $ret_data = eval {$self->_execute_command( $res, $params );};
  1217. if($@) {
  1218. if($@ =~ /(An element could not be located on the page using the given search parameters)/) {
  1219. # give details on what element wasn't found
  1220. $@ = "$1: $query,$using";
  1221. local @CARP_NOT = ("Selenium::Remote::Driver",@CARP_NOT);
  1222. croak $@;
  1223. } else {
  1224. # re throw if the exception wasn't what we expected
  1225. die $@;
  1226. }
  1227. }
  1228. my $elem_obj_arr;
  1229. my $i = 0;
  1230. foreach (@$ret_data) {
  1231. $elem_obj_arr->[$i] = new Selenium::Remote::WebElement($_->{ELEMENT}, $self);
  1232. $i++;
  1233. }
  1234. return wantarray?@{$elem_obj_arr}:$elem_obj_arr;
  1235. }
  1236. else {
  1237. croak "Bad method, expected - class, class_name, css, id, link,
  1238. link_text, partial_link_text, name, tag_name, xpath";
  1239. }
  1240. }
  1241. =head2 get_active_element
  1242. Description:
  1243. Get the element on the page that currently has focus.. The located element
  1244. will be returned as a WebElement object.
  1245. Output:
  1246. Selenium::Remote::WebElement - WebElement Object
  1247. Usage:
  1248. $driver->get_active_element();
  1249. =cut
  1250. sub get_active_element {
  1251. my ($self) = @_;
  1252. my $res = { 'command' => 'getActiveElement' };
  1253. my $ret_data = eval { $self->_execute_command($res) };
  1254. if ($@) {
  1255. croak $@;
  1256. } else {
  1257. return new Selenium::Remote::WebElement($ret_data->{ELEMENT}, $self);
  1258. }
  1259. }
  1260. =head2 send_modifier
  1261. Description:
  1262. Send an event to the active element to depress or release a modifier key.
  1263. Input: 2
  1264. Required:
  1265. 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
  1266. isdown - Boolean/String - Whether to generate a key down or key up
  1267. Usage:
  1268. $driver->send_modifier('Alt','down');
  1269. $elem->send_keys('c');
  1270. $driver->send_modifier('Alt','up');
  1271. or
  1272. $driver->send_modifier('Alt',1);
  1273. $elem->send_keys('c');
  1274. $driver->send_modifier('Alt',0);
  1275. =cut
  1276. sub send_modifier {
  1277. my ($self,$modifier,$isdown) = @_;
  1278. if($isdown =~ /(down|up)/) {
  1279. $isdown = $isdown =~ /down/ ? 1:0;
  1280. }
  1281. my $res = {'command' => 'sendModifier'};
  1282. my $params = {value => $modifier,
  1283. isdown => $isdown};
  1284. return $self->_execute_command($res,$params);
  1285. }
  1286. =head2 compare_elements
  1287. Description:
  1288. Test if two element IDs refer to the same DOM element.
  1289. Input: 2
  1290. Required:
  1291. Selenium::Remote::WebElement - WebElement Object
  1292. Selenium::Remote::WebElement - WebElement Object
  1293. Output:
  1294. BOOLEAN
  1295. Usage:
  1296. $driver->compare_elements($elem_obj1, $elem_obj2);
  1297. =cut
  1298. sub compare_elements {
  1299. my ($self, $elem1, $elem2) = @_;
  1300. my $res = { 'command' => 'elementEquals',
  1301. 'id' => $elem1->{id},
  1302. 'other' => $elem2->{id}
  1303. };
  1304. return $self->_execute_command($res);
  1305. }
  1306. =head2 click
  1307. Description:
  1308. Click any mouse button (at the coordinates set by the last moveto command).
  1309. Input:
  1310. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1311. defaults to 'LEFT'
  1312. Usage:
  1313. $driver->click('LEFT');
  1314. $driver->click(1); #MIDDLE
  1315. $driver->click('RIGHT');
  1316. $driver->click; #Defaults to left
  1317. =cut
  1318. sub click {
  1319. my ($self,$button) = @_;
  1320. my $button_enum = {LEFT=>0,MIDDLE=>1,RIGHT=>2};
  1321. if(defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i) {
  1322. $button = $button_enum->{uc $1};
  1323. } elsif(defined $button && $button =~ /(0|1|2)/) {
  1324. $button = $1;
  1325. } else {
  1326. $button = 0;
  1327. }
  1328. my $res = { 'command' => 'click' };
  1329. my $params = { 'button' => $button };
  1330. return $self->_execute_command($res,$button);
  1331. }
  1332. =head2 double_click
  1333. Description:
  1334. Double-clicks at the current mouse coordinates (set by moveto).
  1335. Usage:
  1336. $driver->double_click;
  1337. =cut
  1338. sub double_click {
  1339. my ($self) = @_;
  1340. my $res = { 'command' => 'doubleClick' };
  1341. return $self->_execute_command($res);
  1342. }
  1343. =head2 button_down
  1344. Description:
  1345. Click and hold the left mouse button (at the coordinates set by the
  1346. last moveto command). Note that the next mouse-related command that
  1347. should follow is buttondown . Any other mouse command (such as click
  1348. or another call to buttondown) will yield undefined behaviour.
  1349. Usage:
  1350. $self->button_down;
  1351. =cut
  1352. sub button_down {
  1353. my ($self) = @_;
  1354. my $res = { 'command' => 'buttonDown' };
  1355. return $self->_execute_command($res);
  1356. }
  1357. =head2 button_up
  1358. Description:
  1359. Releases the mouse button previously held (where the mouse is
  1360. currently at). Must be called once for every buttondown command
  1361. issued. See the note in click and buttondown about implications of
  1362. out-of-order commands.
  1363. Usage:
  1364. $self->button_up;
  1365. =cut
  1366. sub button_up {
  1367. my ($self) = @_;
  1368. my $res = { 'command' => 'buttonUp' };
  1369. return $self->_execute_command($res);
  1370. }
  1371. 1;
  1372. __END__
  1373. =head1 SEE ALSO
  1374. For more information about Selenium , visit the website at
  1375. L<http://code.google.com/p/selenium/>.
  1376. Also checkout project's wiki page at
  1377. L<https://github.com/aivaturi/Selenium-Remote-Driver/wiki>.
  1378. =head1 BUGS
  1379. The Selenium issue tracking system is available online at
  1380. L<http://github.com/aivaturi/Selenium-Remote-Driver/issues>.
  1381. =head1 AUTHOR
  1382. Perl Bindings for Selenium Remote Driver by Aditya Ivaturi C<< <ivaturi@gmail.com> >>
  1383. =head1 ACKNOWLEDGEMENTS
  1384. The following people have contributed to this module. (Thanks!)
  1385. =over 4
  1386. =item * Gordon Child
  1387. =item * Phil Kania
  1388. =item * Phil Mitchell
  1389. =item * Allen Lew
  1390. =item * Tom Hukins
  1391. =back
  1392. =head1 LICENSE
  1393. Copyright (c) 2010-2011 Aditya Ivaturi, Gordon Child
  1394. Licensed under the Apache License, Version 2.0 (the "License");
  1395. you may not use this file except in compliance with the License.
  1396. You may obtain a copy of the License at
  1397. http://www.apache.org/licenses/LICENSE-2.0
  1398. Unless required by applicable law or agreed to in writing, software
  1399. distributed under the License is distributed on an "AS IS" BASIS,
  1400. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1401. See the License for the specific language governing permissions and
  1402. limitations under the License.