Driver.pm 53 KB

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