1
0

Driver.pm 59 KB

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