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