Driver.pm 49 KB

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