Driver.pm 56 KB

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