1
0

Driver.pm 56 KB

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