1
0

Driver.pm 55 KB

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