1
0

Driver.pm 56 KB

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