Driver.pm 60 KB

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