Driver.pm 52 KB

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