Driver.pm 51 KB

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