Driver.pm 49 KB

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