1
0

Driver.pm 53 KB

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