Driver.pm 52 KB

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