Driver.pm 53 KB

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