Driver.pm 53 KB

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