Driver.pm 56 KB

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