1
0

Driver.pm 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985
  1. package Selenium::Remote::Driver;
  2. use strict;
  3. use warnings;
  4. # ABSTRACT: Perl Client for Selenium Remote Driver
  5. use Moo;
  6. use Try::Tiny;
  7. use 5.006;
  8. use v5.10.0; # Before 5.006, v5.10.0 would not be understood.
  9. # See http://perldoc.perl.org/5.10.0/functions/use.html#use-VERSION
  10. # and http://www.dagolden.com/index.php/369/version-numbers-should-be-boring/
  11. # for details.
  12. use Carp;
  13. our @CARP_NOT;
  14. use IO::String;
  15. use Archive::Zip qw( :ERROR_CODES );
  16. use Scalar::Util;
  17. use Selenium::Remote::RemoteConnection;
  18. use Selenium::Remote::Commands;
  19. use Selenium::Remote::WebElement;
  20. use File::Spec::Functions ();
  21. use File::Basename qw(basename);
  22. use Sub::Install ();
  23. use MIME::Base64 ();
  24. use Time::HiRes qw(usleep);
  25. use constant FINDERS => {
  26. class => 'class name',
  27. class_name => 'class name',
  28. css => 'css selector',
  29. id => 'id',
  30. link => 'link text',
  31. link_text => 'link text',
  32. name => 'name',
  33. partial_link_text => 'partial link text',
  34. tag_name => 'tag name',
  35. xpath => 'xpath',
  36. };
  37. =for Pod::Coverage BUILD
  38. =for Pod::Coverage DEMOLISH
  39. =head1 SYNOPSIS
  40. use Selenium::Remote::Driver;
  41. my $driver = Selenium::Remote::Driver->new;
  42. $driver->get('http://www.google.com');
  43. print $driver->get_title();
  44. $driver->quit();
  45. =cut
  46. =head1 DESCRIPTION
  47. Selenium is a test tool that allows you to write
  48. automated web application UI tests in any programming language against
  49. any HTTP website using any mainstream JavaScript-enabled browser. This module is
  50. an implementation of the client for the Remote driver that Selenium provides.
  51. You can find bindings for other languages at this location:
  52. L<http://code.google.com/p/selenium/>
  53. This module sends commands directly to the Server using HTTP. Using this module
  54. together with the Selenium Server, you can automatically control any supported
  55. browser. To use this module, you need to have already downloaded and started
  56. the Selenium Server (Selenium Server is a Java application).
  57. =cut
  58. =head1 USAGE
  59. =head2 Without Standalone Server
  60. As of v0.25, it's possible to use this module without a standalone
  61. server - that is, you would not need the JRE or the JDK to run your
  62. Selenium tests. See L<Selenium::Chrome>, L<Selenium::PhantomJS>, and
  63. L<Selenium::Firefox> for details. If you'd like additional browsers
  64. besides these, give us a holler over in
  65. L<Github|https://github.com/gempesaw/Selenium-Remote-Driver/issues>.
  66. =head2 Remote Driver Response
  67. Selenium::Remote::Driver uses the
  68. L<JsonWireProtocol|http://code.google.com/p/selenium/wiki/JsonWireProtocol>
  69. to communicate with the Selenium Server. If an error occurs while
  70. executing the command then the server sends back an HTTP error code
  71. with a JSON encoded reponse that indicates the precise L<Response
  72. Error
  73. Code|http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes>. The
  74. module will then croak with the error message associated with this
  75. code. If no error occurred, then the subroutine called will return the
  76. value sent back from the server (if a return value was sent).
  77. So a rule of thumb while invoking methods on the driver is if the method did not
  78. croak when called, then you can safely assume the command was successful even if
  79. nothing was returned by the method.
  80. =head2 WebElement
  81. Selenium Webdriver represents all the HTML elements as WebElement, which is
  82. in turn represented by L<Selenium::Remote::WebElement> module. So any method that
  83. deals with WebElements will return and/or expect WebElement object. The POD for
  84. that module describes all the methods that perform various actions on the
  85. WebElements like click, submit etc.
  86. To interact with any WebElement you have to first "find" it, read the POD for
  87. find_element or find_elements for further info. Once you find the required element
  88. then you can perform various actions. If you don't call find_* method first, all
  89. your further actions will fail for that element. Finally, just remember that you
  90. don't have to instantiate WebElement objects at all - they will be automatically
  91. created when you use the find_* methods.
  92. A sub-class of Selenium::Remote::WebElement may be used instead of Selenium::Remote::WebElement,
  93. by providing that class name as an option the constructor:
  94. my $driver = Selenium::Remote::Driver->new( webelement_class => ... );
  95. For example, a testing-subclass may extend the web-element object with testing methods.
  96. =head2 LWP Read Timeout errors
  97. It's possible to make Selenium calls that take longer than the default
  98. L<LWP::UserAgent> timeout. For example, setting the asynchronous
  99. script timeout greater than the LWP::UserAgent timeout and then
  100. executing a long running asynchronous snippet of javascript will
  101. immediately trigger an error like:
  102. Error while executing command: executeAsyncScript: Server returned
  103. error message read timeout at...
  104. You can get around this by configuring LWP's timeout value, either by
  105. constructing your own LWP and passing it in to ::Driver during
  106. instantiation
  107. my $timeout_ua = LWP::UserAgent->new;
  108. $timeout_ua->timeout(360); # this value is in seconds!
  109. my $d = Selenium::Remote::Driver->new( ua => $timeout_ua );
  110. or by configuring the timeout on the fly as necessary:
  111. use feature qw/say/;
  112. use Selenium::Remote::Driver;
  113. my $d = Selenium::Remote::Driver->new;
  114. say $d->ua->timeout; # 180 seconds is the default
  115. $d->ua->timeout(2); # LWP wants seconds, not milliseconds!
  116. $d->set_timeout('script', 1000); # S::R::D wants milliseconds!
  117. # Async scripts only return when the callback is invoked. Since there
  118. # is no callback here, Selenium will block for the entire duration of
  119. # the async timeout script. This will hit Selenium's async script
  120. # timeout before hitting LWP::UserAgent's read timeout
  121. $d->execute_async_script('return "hello"');
  122. $d->quit;
  123. =head1 TESTING
  124. If are writing automated tests using this module, you may be
  125. interested in L<Test::Selenium::Remote::Driver> which is also included
  126. in this distribution. It includes convenience testing methods for many
  127. of the selenum methods available here.
  128. Your other option is to use this module in conjunction with your
  129. choice of testing modules, like L<Test::Spec> or L<Test::More> as
  130. you please.
  131. =head1 CONSTRUCTOR
  132. =head2 new
  133. Dies if communication with the selenium server cannot be established.
  134. Input: (all optional)
  135. Desired capabilities - HASH - Following options are accepted:
  136. =over 4
  137. =item B<remote_server_addr> - <string> - IP or FQDN of the Webdriver server machine. Default: 'localhost'
  138. =item B<port> - <string> - Port on which the Webdriver server is listening. Default: 4444
  139. =item B<browser_name> - <string> - desired browser string: {phantomjs|firefox|internet explorer|htmlunit|iphone|chrome}
  140. =item B<version> - <string> - desired browser version number
  141. =item B<platform> - <string> - desired platform: {WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}
  142. =item B<accept_ssl_certs> - <boolean> - whether SSL certs should be accepted, default is true.
  143. =item B<firefox_profile> - Profile - Use Selenium::Firefox::Profile to create a Firefox profile for the browser to use
  144. =item B<proxy> - HASH - Proxy configuration with the following keys:
  145. =item B<javascript> - <boolean> - Whether or not to use Javascript. You probably won't disable this, as you would be using L<WWW::Mechanize> instead. Default: True
  146. =item B<auto_close> - <boolean> - Whether to automatically close the browser session on the server when the object goes out of scope. Default: False.
  147. =item B<default_finder> - <string> - Default method by which to evaluate selectors. Default: 'xpath'
  148. =item B<session_id> - <string> - Provide a Session ID to highjack a browser session on the remote server. Useful for micro-optimizers. Default: undef
  149. =over 4
  150. =item B<proxyType> - <string> - REQUIRED, Possible values are:
  151. direct - A direct connection - no proxy in use,
  152. manual - Manual proxy settings configured, e.g. setting a proxy for HTTP, a proxy for FTP, etc,
  153. pac - Proxy autoconfiguration from a URL,
  154. autodetect - proxy autodetection, probably with WPAD,
  155. system - Use system settings
  156. =item B<proxyAutoconfigUrl> - <string> - REQUIRED if proxyType is 'pac', ignored otherwise. Expected format: http://hostname.com:1234/pacfile or file:///path/to/pacfile
  157. =item B<ftpProxy> - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  158. =item B<httpProxy> - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  159. =item B<sslProxy> - <string> - OPTIONAL, ignored if proxyType is not 'manual'. Expected format: hostname.com:1234
  160. =back
  161. =item B<extra_capabilities> - HASH - Any other extra capabilities. Accepted keys will vary by browser.
  162. =back
  163. You can also specify some options in the constructor hash that are
  164. not part of the browser-related desired capabilities.
  165. =over 4
  166. =item B<auto_close> - <boolean> - whether driver should end session on remote server on close.
  167. =item B<base_url> - <string> - OPTIONAL, base url for the website Selenium acts on. This can save you from repeating the domain in every call to $driver->get()
  168. =item B<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}
  169. =item B<inner_window_size> - <aref[Int]> - An array ref [ height, width ] that the browser window should use as its initial size immediately after instantiation
  170. =item B<error_handler> - CODEREF - A CODEREF that we will call in event of any exceptions. See L</error_handler> for more details.
  171. =item B<webelement_class> - <string> - sub-class of Selenium::Remote::WebElement if you wish to use an alternate WebElement class.
  172. =item B<ua> - LWP::UserAgent instance - if you wish to use a specific $ua, like from Test::LWP::UserAgent
  173. =back
  174. Output:
  175. Remote Driver object
  176. Usage:
  177. my $driver = Selenium::Remote::Driver->new;
  178. or
  179. my $driver = Selenium::Remote::Driver->new('browser_name' => 'firefox',
  180. 'platform' => 'MAC');
  181. or (for Firefox 47 or lower on Selenium 3+)
  182. my $driver = Selenium::Remote::Driver->new('browser_name' => 'firefox',
  183. 'platform' => 'MAC',
  184. 'extra_capabilities' => {
  185. 'marionette' => \0,
  186. });
  187. or
  188. my $driver = Selenium::Remote::Driver->new('remote_server_addr' => '10.10.1.1',
  189. 'port' => '2222',
  190. 'auto_close' => 0);
  191. or
  192. my $driver = Selenium::Remote::Driver->new('browser_name' =>'chrome',
  193. 'extra_capabilities' => {
  194. 'chromeOptions' => {
  195. 'args' => [
  196. 'window-size=1260,960',
  197. 'incognito'
  198. ],
  199. 'prefs' => {
  200. 'session' => {
  201. 'restore_on_startup' => 4,
  202. 'urls_to_restore_on_startup' => [
  203. 'http://www.google.com',
  204. 'http://docs.seleniumhq.org'
  205. ]},
  206. 'first_run_tabs' => [
  207. 'http://www.google.com',
  208. 'http://docs.seleniumhq.org'
  209. ]
  210. }
  211. }
  212. });
  213. or
  214. my $driver = Selenium::Remote::Driver->new('proxy' => {'proxyType' => 'manual', 'httpProxy' => 'myproxy.com:1234'});
  215. or
  216. my $driver = Selenium::Remote::Driver->new('default_finder' => 'css');
  217. =head3 error_handler
  218. =head3 clear_error_handler
  219. OPTIONAL constructor arg & associated setter/clearer: if you wish to
  220. install your own error handler, you may pass a code ref in to
  221. C<error_handler> during instantiation like follows:
  222. my $driver = Selenium::Remote::Driver->new(
  223. error_handler => sub { print $_[1]; croak 'goodbye'; }
  224. );
  225. Additionally, you can set and/or clear it at any time on an
  226. already-instantiated driver:
  227. # later, change the error handler to something else
  228. $driver->error_handler( sub { print $_[1]; croak 'hello'; } );
  229. # stop handling errors manually and use the default S:R:D behavior
  230. # (we will croak about the exception)
  231. $driver->clear_error_handler;
  232. Your error handler will receive two arguments: the first argument is
  233. the C<$driver> object itself, and the second argument is the exception
  234. message and stack trace in one multiline string.
  235. B<N.B.>: If you set your own error handler, you are entirely
  236. responsible for handling webdriver exceptions, _including_ croaking
  237. behavior. That is, when you set an error handler, we will no longer
  238. croak on Webdriver exceptions - it's up to you to do so. For
  239. consistency with the standard S:R:D behavior, we recommend your error
  240. handler also croak when it's done, especially since your test
  241. shouldn't be running into unexpected errors. Catching specific or
  242. desired errors in your error handler makes sense, but not croaking at
  243. all can leave you in unfamiliar territory. Reaching an unexpected
  244. exception might mean your test has gone off the rails, and the further
  245. your test gets from the source of the of the exception, the harder it
  246. will be to debug.
  247. B<N.B.>: Four methods will still croak on their own: L</find_element>,
  248. L</find_elements>, L</find_child_element>, and
  249. L</find_child_elements>. If these methods throw a Webdriver Exception,
  250. your error handler _will still be_ invoked inside an C<eval>, and then
  251. they'll croak with their own error message that indicates the locator
  252. and strategy used. So, your strategies for avoiding exceptions when
  253. finding elements do not change (either use find_elements and check
  254. the returned array size, wrap your calls to find_element* in an
  255. C<eval>, or use the parameterized versions find_element_*).
  256. =head2 new_from_caps
  257. Description:
  258. For experienced users who want complete control over the desired
  259. capabilities, use this alternative constructor along with the
  260. C<desired_capabilities> hash key in the init hash. Unlike "new",
  261. this constructor will not assume any defaults for your desired
  262. capabilities.
  263. This alternate constructor IGNORES all other browser-related
  264. desiredCapability options; the only options that will be respected
  265. are those that are NOT part of the Capabilities JSON Object as
  266. described in the Json Wire Protocol.
  267. Input:
  268. The only respected keys in the input hash are:
  269. desired_capabilities - HASHREF - defaults to {}
  270. remote_server_addr - STRING - defaults to localhost
  271. port - INTEGER - defaults to 4444
  272. default_finder - STRING - defaults to xpath
  273. webelement_class - STRING - defaults to Selenium::Remote::WebElement
  274. auto_close - BOOLEAN - defaults to 1
  275. error_handler - CODEREF - defaults to croaking on exceptions
  276. Except for C<desired_capabilities>, these keys perform exactly the
  277. same as listed in the regular "new" constructor.
  278. The hashref you pass in as desired_capabilities only gets json
  279. encoded before being passed to the Selenium server; no default
  280. options of any sort will be added.
  281. This means you must handle normalization and casing of the input
  282. options (like "browser_name" vs "browserName") and take care of
  283. things like encoding the firefox profile if applicable. More
  284. information about the desired capabilities object is available on
  285. the Selenium wiki:
  286. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  287. Output:
  288. Remote Driver object
  289. Usage:
  290. my $driver = Selenium::Remote::Driver->new_from_caps(
  291. 'desired_capabilities' => {'browserName' => 'firefox'}
  292. );
  293. The above would generate a POST to the webdriver server at
  294. localhost:4444 with the exact payload of '{"desiredCapabilities":
  295. {"browserName": "firefox" }}'.
  296. =for Pod::Coverage has_base_url
  297. =for Pod::Coverage has_desired_capabilities
  298. =for Pod::Coverage has_error_handler
  299. =for Pod::Coverage has_firefox_profile
  300. =for Pod::Coverage has_inner_window_size
  301. =for Pod::Coverage has_javascript
  302. =for Pod::Coverage has_port
  303. =for Pod::Coverage has_remote_server_addr
  304. =cut
  305. has 'remote_server_addr' => (
  306. is => 'rw',
  307. coerce => sub { ( defined($_[0]) ? $_[0] : 'localhost' )},
  308. default => sub {'localhost'},
  309. predicate => 1
  310. );
  311. has 'browser_name' => (
  312. is => 'rw',
  313. coerce => sub { ( defined($_[0]) ? $_[0] : 'firefox' )},
  314. default => sub {'firefox'},
  315. );
  316. has 'base_url' => (
  317. is => 'lazy',
  318. coerce => sub {
  319. my $base_url = shift;
  320. $base_url =~ s|/$||;
  321. return $base_url;
  322. },
  323. predicate => 'has_base_url',
  324. );
  325. has 'platform' => (
  326. is => 'rw',
  327. coerce => sub { ( defined($_[0]) ? $_[0] : 'ANY' )},
  328. default => sub {'ANY'},
  329. );
  330. has 'port' => (
  331. is => 'rw',
  332. coerce => sub { ( defined($_[0]) ? $_[0] : '4444' )},
  333. default => sub {'4444'},
  334. predicate => 1
  335. );
  336. has 'version' => (
  337. is => 'rw',
  338. default => sub {''},
  339. );
  340. has 'webelement_class' => (
  341. is => 'rw',
  342. default => sub {'Selenium::Remote::WebElement'},
  343. );
  344. has 'default_finder' => (
  345. is => 'rw',
  346. coerce => sub { __PACKAGE__->FINDERS->{ $_[0] } },
  347. default => sub {'xpath'},
  348. );
  349. has 'session_id' => (
  350. is => 'rw',
  351. default => sub {undef},
  352. );
  353. has 'remote_conn' => (
  354. is => 'lazy',
  355. builder => sub {
  356. my $self = shift;
  357. return Selenium::Remote::RemoteConnection->new(
  358. remote_server_addr => $self->remote_server_addr,
  359. port => $self->port,
  360. ua => $self->ua,
  361. wd_context_prefix => $self->wd_context_prefix
  362. );
  363. },
  364. );
  365. has 'error_handler' => (
  366. is => 'rw',
  367. coerce => sub {
  368. my ($maybe_coderef) = @_;
  369. if ( ref($maybe_coderef) eq 'CODE' ) {
  370. return $maybe_coderef;
  371. }
  372. else {
  373. croak 'The error handler must be a code ref.';
  374. }
  375. },
  376. clearer => 1,
  377. predicate => 1
  378. );
  379. has 'ua' => (
  380. is => 'lazy',
  381. builder => sub { return LWP::UserAgent->new }
  382. );
  383. has 'commands' => (
  384. is => 'lazy',
  385. builder => sub {
  386. return Selenium::Remote::Commands->new;
  387. },
  388. );
  389. has 'auto_close' => (
  390. is => 'rw',
  391. coerce => sub { ( defined($_[0]) ? $_[0] : 1 )},
  392. default => sub {1},
  393. );
  394. has 'pid' => (
  395. is => 'lazy',
  396. builder => sub { return $$ }
  397. );
  398. has 'javascript' => (
  399. is => 'rw',
  400. coerce => sub { $_[0] ? JSON::true : JSON::false },
  401. default => sub { return JSON::true }
  402. );
  403. has 'accept_ssl_certs' => (
  404. is => 'rw',
  405. coerce => sub { $_[0] ? JSON::true : JSON::false },
  406. default => sub { return JSON::true }
  407. );
  408. has 'proxy' => (
  409. is => 'rw',
  410. coerce => sub {
  411. my $proxy = $_[0];
  412. if ( $proxy->{proxyType} =~ /^pac$/i ) {
  413. if ( not defined $proxy->{proxyAutoconfigUrl} ) {
  414. croak "proxyAutoconfigUrl not provided\n";
  415. }
  416. elsif ( not( $proxy->{proxyAutoconfigUrl} =~ /^(http|file)/g ) ) {
  417. croak "proxyAutoconfigUrl should be of format http:// or file://";
  418. }
  419. if ( $proxy->{proxyAutoconfigUrl} =~ /^file/ ) {
  420. my $pac_url = $proxy->{proxyAutoconfigUrl};
  421. my $file = $pac_url;
  422. $file =~ s{^file://}{};
  423. if (! -e $file) {
  424. warn "proxyAutoConfigUrl file does not exist: '$pac_url'";
  425. }
  426. }
  427. }
  428. $proxy;
  429. },
  430. );
  431. has 'extra_capabilities' => (
  432. is => 'rw',
  433. default => sub { {} }
  434. );
  435. has 'firefox_profile' => (
  436. is => 'rw',
  437. coerce => sub {
  438. my $profile = shift;
  439. unless (Scalar::Util::blessed($profile)
  440. && $profile->isa('Selenium::Firefox::Profile')) {
  441. croak "firefox_profile should be a Selenium::Firefox::Profile\n";
  442. }
  443. return $profile;
  444. },
  445. predicate => 'has_firefox_profile',
  446. clearer => 1
  447. );
  448. has 'desired_capabilities' => (
  449. is => 'lazy',
  450. predicate => 'has_desired_capabilities'
  451. );
  452. has 'inner_window_size' => (
  453. is => 'lazy',
  454. predicate => 1,
  455. coerce => sub {
  456. my $size = shift;
  457. croak "inner_window_size must have two elements: [ height, width ]"
  458. unless scalar @$size == 2;
  459. foreach my $dim (@$size) {
  460. croak 'inner_window_size only accepts integers, not: ' . $dim
  461. unless Scalar::Util::looks_like_number($dim);
  462. }
  463. return $size;
  464. },
  465. );
  466. # At the time of writing, Geckodriver uses a different endpoint than
  467. # the java bindings for executing synchronous and asynchronous
  468. # scripts. As a matter of fact, Geckodriver does conform to the W3C
  469. # spec, but as are bound to support both while the java bindings
  470. # transition to full spec support, we need some way to handle the
  471. # difference.
  472. has '_execute_script_suffix' => (
  473. is => 'lazy',
  474. default => ''
  475. );
  476. with 'Selenium::Remote::Finders';
  477. with 'Selenium::Remote::Driver::CanSetWebdriverContext';
  478. sub BUILD {
  479. my $self = shift;
  480. if ( !( defined $self->session_id ) ) {
  481. if ($self->has_desired_capabilities) {
  482. $self->new_desired_session( $self->desired_capabilities );
  483. }
  484. else {
  485. # Connect to remote server & establish a new session
  486. $self->new_session( $self->extra_capabilities );
  487. }
  488. }
  489. if ( !( defined $self->session_id ) ) {
  490. croak "Could not establish a session with the remote server\n";
  491. }
  492. elsif ($self->has_inner_window_size) {
  493. my $size = $self->inner_window_size;
  494. $self->set_inner_window_size(@$size);
  495. }
  496. # Setup non-croaking, parameter versions of finders
  497. foreach my $by (keys %{ $self->FINDERS }) {
  498. my $finder_name = 'find_element_by_' . $by;
  499. # In case we get instantiated multiple times, we don't want to
  500. # install into the name space every time.
  501. unless ($self->can($finder_name)) {
  502. my $find_sub = $self->_build_find_by($by);
  503. Sub::Install::install_sub({
  504. code => $find_sub,
  505. into => __PACKAGE__,
  506. as => $finder_name,
  507. });
  508. }
  509. }
  510. }
  511. sub new_from_caps {
  512. my ($self, %args) = @_;
  513. if (not exists $args{desired_capabilities}) {
  514. $args{desired_capabilities} = {};
  515. }
  516. return $self->new(%args);
  517. }
  518. sub DEMOLISH {
  519. my ($self, $in_global_destruction) = @_;
  520. return if $$ != $self->pid;
  521. return if $in_global_destruction;
  522. $self->quit() if ( $self->auto_close && defined $self->session_id );
  523. }
  524. # We install an 'around' because we can catch more exceptions this way
  525. # than simply wrapping the explicit croaks in _execute_command.
  526. around '_execute_command' => sub {
  527. my $orig = shift;
  528. my $self = shift;
  529. # copy @_ because it gets lost in the way
  530. my @args = @_;
  531. my $return_value;
  532. try {
  533. $return_value = $orig->($self,@args);
  534. }
  535. catch {
  536. if ($self->has_error_handler) {
  537. $self->error_handler->($self,$_);
  538. }
  539. else {
  540. croak $_;
  541. }
  542. };
  543. return $return_value;
  544. };
  545. # This is an internal method used the Driver & is not supposed to be used by
  546. # end user. This method is used by Driver to set up all the parameters
  547. # (url & JSON), send commands & receive processed response from the server.
  548. sub _execute_command {
  549. my ( $self, $res, $params ) = @_;
  550. $res->{'session_id'} = $self->session_id;
  551. my $resource = $self->commands->get_params($res);
  552. if ($resource) {
  553. $params = {} unless $params;
  554. my $resp = $self->remote_conn->request( $resource, $params);
  555. if ( ref($resp) eq 'HASH' ) {
  556. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'OK' ) {
  557. return $resp->{cmd_return};
  558. }
  559. else {
  560. my $msg = "Error while executing command";
  561. if ( $resp->{cmd_error} ) {
  562. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  563. }
  564. elsif ( $resp->{cmd_return} ) {
  565. if ( ref( $resp->{cmd_return} ) eq 'HASH' ) {
  566. $msg .= ": $res->{command}"
  567. if $res->{command};
  568. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  569. if $resp->{cmd_return}->{error}->{msg};
  570. $msg .= ": $resp->{cmd_return}->{message}"
  571. if $resp->{cmd_return}->{message};
  572. }
  573. else {
  574. $msg .= ": $resp->{cmd_return}";
  575. }
  576. }
  577. croak $msg;
  578. }
  579. }
  580. return $resp;
  581. }
  582. else {
  583. croak "Couldn't retrieve command settings properly\n";
  584. }
  585. }
  586. =head1 METHODS
  587. =head2 new_session (extra_capabilities)
  588. Make a new session on the server.
  589. Called by new(), not intended for regular use.
  590. Occaisonally handy for recovering from brower crashes.
  591. =cut
  592. sub new_session {
  593. my ( $self, $extra_capabilities ) = @_;
  594. $extra_capabilities ||= {};
  595. my $args = {
  596. 'desiredCapabilities' => {
  597. 'browserName' => $self->browser_name,
  598. 'platform' => $self->platform,
  599. 'javascriptEnabled' => $self->javascript,
  600. 'version' => $self->version,
  601. 'acceptSslCerts' => $self->accept_ssl_certs,
  602. %$extra_capabilities,
  603. },
  604. };
  605. if ( defined $self->proxy ) {
  606. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  607. }
  608. if ($args->{desiredCapabilities}->{browserName} =~ /firefox/i
  609. && $self->has_firefox_profile) {
  610. $args->{desiredCapabilities}->{firefox_profile} = $self->firefox_profile->_encode;
  611. }
  612. $self->_request_new_session($args);
  613. }
  614. =head2 new_desired_session(capabilities)
  615. Basically the same as new_session, but with caps.
  616. Sort of an analog to new_from_caps.
  617. =cut
  618. sub new_desired_session {
  619. my ( $self, $caps ) = @_;
  620. $self->_request_new_session({
  621. desiredCapabilities => $caps
  622. });
  623. }
  624. sub _request_new_session {
  625. my ( $self, $args ) = @_;
  626. # geckodriver has not yet implemented the GET /status endpoint
  627. # https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver/status
  628. if (! $self->isa('Selenium::Firefox')) {
  629. $self->remote_conn->check_status();
  630. }
  631. # command => 'newSession' to fool the tests of commands implemented
  632. # TODO: rewrite the testing better, this is so fragile.
  633. my $resource_new_session = {
  634. method => $self->commands->get_method('newSession'),
  635. url => $self->commands->get_url('newSession'),
  636. no_content_success => $self->commands->get_no_content_success('newSession'),
  637. };
  638. my $rc = $self->remote_conn;
  639. my $resp = $rc->request(
  640. $resource_new_session,
  641. $args,
  642. );
  643. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  644. $self->session_id( $resp->{'sessionId'} );
  645. }
  646. else {
  647. my $error = 'Could not create new session';
  648. if (ref $resp->{cmd_return} eq 'HASH') {
  649. $error .= ': ' . $resp->{cmd_return}->{message};
  650. }
  651. else {
  652. $error .= ': ' . $resp->{cmd_return};
  653. }
  654. croak $error;
  655. }
  656. }
  657. =head2 debug_on
  658. Description:
  659. Turns on debugging mode and the driver will print extra info like request
  660. and response to stdout. Useful, when you want to see what is being sent to
  661. the server & what response you are getting back.
  662. Usage:
  663. $driver->debug_on;
  664. =cut
  665. sub debug_on {
  666. my ($self) = @_;
  667. $self->remote_conn->debug(1);
  668. }
  669. =head2 debug_off
  670. Description:
  671. Turns off the debugging mode.
  672. Usage:
  673. $driver->debug_off;
  674. =cut
  675. sub debug_off {
  676. my ($self) = @_;
  677. $self->remote_conn->debug(0);
  678. }
  679. =head2 get_sessions
  680. Description:
  681. Returns a list of the currently active sessions. Each session will be
  682. returned as an array of Hashes with the following keys:
  683. 'id' : The session ID
  684. 'capabilities: An object describing session's capabilities
  685. Output:
  686. Array of Hashes
  687. Usage:
  688. print Dumper $driver->get_sessions();
  689. =cut
  690. sub get_sessions {
  691. my ($self) = @_;
  692. my $res = { 'command' => 'getSessions' };
  693. return $self->_execute_command($res);
  694. }
  695. =head2 status
  696. Description:
  697. Query the server's current status. All server implementations
  698. should return two basic objects describing the server's current
  699. platform and when the server was built.
  700. Output:
  701. Hash ref
  702. Usage:
  703. print Dumper $driver->status;
  704. =cut
  705. sub status {
  706. my ($self) = @_;
  707. my $res = { 'command' => 'status' };
  708. return $self->_execute_command($res);
  709. }
  710. =head2 get_alert_text
  711. Description:
  712. Gets the text of the currently displayed JavaScript alert(), confirm()
  713. or prompt() dialog.
  714. Example
  715. my $string = $driver->get_alert_text;
  716. =cut
  717. sub get_alert_text {
  718. my ($self) = @_;
  719. my $res = { 'command' => 'getAlertText' };
  720. return $self->_execute_command($res);
  721. }
  722. =head2 send_keys_to_active_element
  723. Description:
  724. Send a sequence of key strokes to the active element. This command is
  725. similar to the send keys command in every aspect except the implicit
  726. termination: The modifiers are not released at the end of the call.
  727. Rather, the state of the modifier keys is kept between calls, so mouse
  728. interactions can be performed while modifier keys are depressed.
  729. Input: 1
  730. Required:
  731. {ARRAY | STRING} - Array of strings or a string.
  732. Usage:
  733. $driver->send_keys_to_active_element('abcd', 'efg');
  734. $driver->send_keys_to_active_element('hijk');
  735. or
  736. # include the WDKeys module
  737. use Selenium::Remote::WDKeys;
  738. .
  739. .
  740. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  741. =cut
  742. sub send_keys_to_active_element {
  743. my ( $self, @strings ) = @_;
  744. my $res = { 'command' => 'sendKeysToActiveElement' };
  745. my $params = {
  746. 'value' => \@strings,
  747. };
  748. return $self->_execute_command( $res, $params );
  749. }
  750. =head2 send_keys_to_alert
  751. Synonymous with send_keys_to_prompt
  752. =cut
  753. sub send_keys_to_alert {
  754. return shift->send_keys_to_prompt(@_);
  755. }
  756. =head2 send_keys_to_prompt
  757. Description:
  758. Sends keystrokes to a JavaScript prompt() dialog.
  759. Input:
  760. {string} keys to send
  761. Example:
  762. $driver->send_keys_to_prompt('hello world');
  763. or
  764. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  765. $driver->send_keys_to_alert("Larry Wall");
  766. $driver->accept_alert;
  767. =cut
  768. sub send_keys_to_prompt {
  769. my ( $self, $keys ) = @_;
  770. my $res = { 'command' => 'sendKeysToPrompt' };
  771. my $params = { 'text' => $keys };
  772. return $self->_execute_command( $res, $params );
  773. }
  774. =head2 accept_alert
  775. Description:
  776. Accepts the currently displayed alert dialog. Usually, this is
  777. equivalent to clicking the 'OK' button in the dialog.
  778. Example:
  779. $driver->accept_alert;
  780. =cut
  781. sub accept_alert {
  782. my ($self) = @_;
  783. my $res = { 'command' => 'acceptAlert' };
  784. return $self->_execute_command($res);
  785. }
  786. =head2 dismiss_alert
  787. Description:
  788. Dismisses the currently displayed alert dialog. For comfirm()
  789. and prompt() dialogs, this is equivalent to clicking the
  790. 'Cancel' button. For alert() dialogs, this is equivalent to
  791. clicking the 'OK' button.
  792. Example:
  793. $driver->dismiss_alert;
  794. =cut
  795. sub dismiss_alert {
  796. my ($self) = @_;
  797. my $res = { 'command' => 'dismissAlert' };
  798. return $self->_execute_command($res);
  799. }
  800. =head2 mouse_move_to_location
  801. Description:
  802. Move the mouse by an offset of the specificed element. If no
  803. element is specified, the move is relative to the current mouse
  804. cursor. If an element is provided but no offset, the mouse will be
  805. moved to the center of the element. If the element is not visible,
  806. it will be scrolled into view.
  807. Output:
  808. STRING -
  809. Usage:
  810. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  811. # 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.
  812. # 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.
  813. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  814. =cut
  815. sub mouse_move_to_location {
  816. my ( $self, %params ) = @_;
  817. $params{element} = $params{element}{id} if exists $params{element};
  818. my $res = { 'command' => 'mouseMoveToLocation' };
  819. return $self->_execute_command( $res, \%params );
  820. }
  821. =head2 move_to
  822. Synonymous with mouse_move_to_location
  823. =cut
  824. sub move_to {
  825. return shift->mouse_move_to_location(@_);
  826. }
  827. =head2 move_action
  828. Description:
  829. Move the mouse similarly to the mouse_move_to_location. But uses the
  830. new webdriver actions API which is supported by geckodriver.
  831. Output:
  832. STRING -
  833. Usage:
  834. # element - the element to move to. Must be specified.
  835. # xoffset - X offset to move to, relative to the center of the element. If not specified, the mouse will move to the middle of the element.
  836. # yoffset - Y offset to move to, relative to the center of the element. If not specified, the mouse will move to the middle of the element.
  837. print $driver->move_action(element => e, xoffset => x, yoffset => y);
  838. =cut
  839. sub move_action {
  840. my ( $self, %args ) = @_;
  841. my $params = {
  842. actions => [{
  843. type => "pointer",
  844. id => 'my pointer move',
  845. "parameters" => { "pointerType" => "mouse" },
  846. actions => [
  847. {
  848. type => "pointerMove",
  849. duration => 0,
  850. x => $args{xoffset} // 0,
  851. y => $args{yoffset} // 0,
  852. origin => {'element-6066-11e4-a52e-4f735466cecf' => $args{element}{id}},
  853. },
  854. ],
  855. }],
  856. };
  857. my $res = { 'command' => 'generalAction' };
  858. return $self->_execute_command( $res, $params );
  859. }
  860. =head2 get_capabilities
  861. Description:
  862. Retrieve the capabilities of the specified session.
  863. Output:
  864. HASH of all the capabilities.
  865. Usage:
  866. my $capab = $driver->get_capabilities();
  867. print Dumper($capab);
  868. =cut
  869. sub get_capabilities {
  870. my $self = shift;
  871. my $res = { 'command' => 'getCapabilities' };
  872. return $self->_execute_command($res);
  873. }
  874. =head2 set_timeout
  875. Description:
  876. Configure the amount of time that a particular type of operation can execute
  877. for before they are aborted and a |Timeout| error is returned to the client.
  878. Input:
  879. type - <STRING> - The type of operation to set the timeout for.
  880. Valid values are:
  881. "script" : for script timeouts,
  882. "implicit" : for modifying the implicit wait timeout
  883. "page load" : for setting a page load timeout.
  884. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  885. commands are permitted to run.
  886. Usage:
  887. $driver->set_timeout('script', 1000);
  888. =cut
  889. sub set_timeout {
  890. my ( $self, $type, $ms ) = @_;
  891. if ( not defined $type ) {
  892. croak "Expecting type";
  893. }
  894. $ms = _coerce_timeout_ms( $ms );
  895. my $res = { 'command' => 'setTimeout' };
  896. my $params = { 'type' => $type, 'ms' => $ms, $type => $ms };
  897. return $self->_execute_command( $res, $params );
  898. }
  899. =head2 set_async_script_timeout
  900. Description:
  901. Set the amount of time, in milliseconds, that asynchronous scripts executed
  902. by execute_async_script() are permitted to run before they are
  903. aborted and a |Timeout| error is returned to the client.
  904. Input:
  905. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  906. commands are permitted to run.
  907. Usage:
  908. $driver->set_async_script_timeout(1000);
  909. =cut
  910. sub set_async_script_timeout {
  911. my ( $self, $ms ) = @_;
  912. $ms = _coerce_timeout_ms( $ms );
  913. my $res = { 'command' => 'setAsyncScriptTimeout' };
  914. my $params = { 'ms' => $ms };
  915. return $self->_execute_command( $res, $params );
  916. }
  917. =head2 set_implicit_wait_timeout
  918. Description:
  919. Set the amount of time the driver should wait when searching for elements.
  920. When searching for a single element, the driver will poll the page until
  921. an element is found or the timeout expires, whichever occurs first.
  922. When searching for multiple elements, the driver should poll the page until
  923. at least one element is found or the timeout expires, at which point it
  924. will return an empty list. If this method is never called, the driver will
  925. default to an implicit wait of 0ms.
  926. This is exactly equivalent to calling L</set_timeout> with a type
  927. arg of C<"implicit">.
  928. Input:
  929. Time in milliseconds.
  930. Output:
  931. Server Response Hash with no data returned back from the server.
  932. Usage:
  933. $driver->set_implicit_wait_timeout(10);
  934. =cut
  935. sub set_implicit_wait_timeout {
  936. my ( $self, $ms ) = @_;
  937. $ms = _coerce_timeout_ms( $ms );
  938. my $res = { 'command' => 'setImplicitWaitTimeout' };
  939. my $params = { 'ms' => $ms };
  940. return $self->_execute_command( $res, $params );
  941. }
  942. =head2 pause
  943. Description:
  944. Pause execution for a specified interval of milliseconds.
  945. Usage:
  946. $driver->pause(10000); # 10 second delay
  947. $driver->pause(); # 1 second delay default
  948. DEPRECATED: consider using Time::HiRes instead.
  949. =cut
  950. sub pause {
  951. my $self = shift;
  952. my $timeout = ( shift // 1000 ) * 1000;
  953. usleep($timeout);
  954. }
  955. =head2 close
  956. Description:
  957. Close the current window.
  958. Usage:
  959. $driver->close();
  960. or
  961. #close a popup window
  962. my $handles = $driver->get_window_handles;
  963. $driver->switch_to_window($handles->[1]);
  964. $driver->close();
  965. $driver->switch_to_window($handles->[0]);
  966. =cut
  967. sub close {
  968. my $self = shift;
  969. my $res = { 'command' => 'close' };
  970. $self->_execute_command($res);
  971. }
  972. =head2 quit
  973. Description:
  974. DELETE the session, closing open browsers. We will try to call
  975. this on our down when we get destroyed, but in the event that we
  976. are demolished during global destruction, we will not be able to
  977. close the browser. For your own unattended and/or complicated
  978. tests, we recommend explicitly calling quit to make sure you're
  979. not leaving orphan browsers around.
  980. Note that as a Moo class, we use a subroutine called DEMOLISH that
  981. takes the place of DESTROY; for more information, see
  982. https://metacpan.org/pod/Moo#DEMOLISH.
  983. Usage:
  984. $driver->quit();
  985. =cut
  986. sub quit {
  987. my $self = shift;
  988. my $res = { 'command' => 'quit' };
  989. $self->_execute_command($res);
  990. $self->session_id(undef);
  991. }
  992. =head2 get_current_window_handle
  993. Description:
  994. Retrieve the current window handle.
  995. Output:
  996. STRING - the window handle
  997. Usage:
  998. print $driver->get_current_window_handle();
  999. =cut
  1000. sub get_current_window_handle {
  1001. my $self = shift;
  1002. my $res = { 'command' => 'getCurrentWindowHandle' };
  1003. return $self->_execute_command($res);
  1004. }
  1005. =head2 get_window_handles
  1006. Description:
  1007. Retrieve the list of window handles used in the session.
  1008. Output:
  1009. ARRAY of STRING - list of the window handles
  1010. Usage:
  1011. print Dumper $driver->get_window_handles;
  1012. or
  1013. # get popup, close, then back
  1014. my $handles = $driver->get_window_handles;
  1015. $driver->switch_to_window($handles->[1]);
  1016. $driver->close;
  1017. $driver->switch_to_window($handles->[0]);
  1018. =cut
  1019. sub get_window_handles {
  1020. my $self = shift;
  1021. my $res = { 'command' => 'getWindowHandles' };
  1022. return $self->_execute_command($res);
  1023. }
  1024. =head2 get_window_size
  1025. Description:
  1026. Retrieve the window size
  1027. Input:
  1028. STRING - <optional> - window handle (default is 'current' window)
  1029. Output:
  1030. HASH - containing keys 'height' & 'width'
  1031. Usage:
  1032. my $window_size = $driver->get_window_size();
  1033. print $window_size->{'height'}, $window_size->('width');
  1034. =cut
  1035. sub get_window_size {
  1036. my ( $self, $window ) = @_;
  1037. $window = ( defined $window ) ? $window : 'current';
  1038. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  1039. return $self->_execute_command($res);
  1040. }
  1041. =head2 get_window_position
  1042. Description:
  1043. Retrieve the window position
  1044. Input:
  1045. STRING - <optional> - window handle (default is 'current' window)
  1046. Output:
  1047. HASH - containing keys 'x' & 'y'
  1048. Usage:
  1049. my $window_size = $driver->get_window_position();
  1050. print $window_size->{'x'}, $window_size->('y');
  1051. =cut
  1052. sub get_window_position {
  1053. my ( $self, $window ) = @_;
  1054. $window = ( defined $window ) ? $window : 'current';
  1055. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  1056. return $self->_execute_command($res);
  1057. }
  1058. =head2 get_current_url
  1059. Description:
  1060. Retrieve the url of the current page
  1061. Output:
  1062. STRING - url
  1063. Usage:
  1064. print $driver->get_current_url();
  1065. =cut
  1066. sub get_current_url {
  1067. my $self = shift;
  1068. my $res = { 'command' => 'getCurrentUrl' };
  1069. return $self->_execute_command($res);
  1070. }
  1071. =head2 navigate
  1072. Description:
  1073. Navigate to a given url. This is same as get() method.
  1074. Input:
  1075. STRING - url
  1076. Usage:
  1077. $driver->navigate('http://www.google.com');
  1078. =cut
  1079. sub navigate {
  1080. my ( $self, $url ) = @_;
  1081. $self->get($url);
  1082. }
  1083. =head2 get
  1084. Description:
  1085. Navigate to a given url
  1086. Input:
  1087. STRING - url
  1088. Usage:
  1089. $driver->get('http://www.google.com');
  1090. =cut
  1091. sub get {
  1092. my ( $self, $url ) = @_;
  1093. if ($self->has_base_url && $url !~ m|://|) {
  1094. $url =~ s|^/||;
  1095. $url = $self->base_url . "/" . $url;
  1096. }
  1097. my $res = { 'command' => 'get' };
  1098. my $params = { 'url' => $url };
  1099. return $self->_execute_command( $res, $params );
  1100. }
  1101. =head2 get_title
  1102. Description:
  1103. Get the current page title
  1104. Output:
  1105. STRING - Page title
  1106. Usage:
  1107. print $driver->get_title();
  1108. =cut
  1109. sub get_title {
  1110. my $self = shift;
  1111. my $res = { 'command' => 'getTitle' };
  1112. return $self->_execute_command($res);
  1113. }
  1114. =head2 go_back
  1115. Description:
  1116. Equivalent to hitting the back button on the browser.
  1117. Usage:
  1118. $driver->go_back();
  1119. =cut
  1120. sub go_back {
  1121. my $self = shift;
  1122. my $res = { 'command' => 'goBack' };
  1123. return $self->_execute_command($res);
  1124. }
  1125. =head2 go_forward
  1126. Description:
  1127. Equivalent to hitting the forward button on the browser.
  1128. Usage:
  1129. $driver->go_forward();
  1130. =cut
  1131. sub go_forward {
  1132. my $self = shift;
  1133. my $res = { 'command' => 'goForward' };
  1134. return $self->_execute_command($res);
  1135. }
  1136. =head2 refresh
  1137. Description:
  1138. Reload the current page.
  1139. Usage:
  1140. $driver->refresh();
  1141. =cut
  1142. sub refresh {
  1143. my $self = shift;
  1144. my $res = { 'command' => 'refresh' };
  1145. return $self->_execute_command($res);
  1146. }
  1147. =head2 javascript
  1148. Description:
  1149. returns true if javascript is enabled in the driver.
  1150. Usage:
  1151. if ($driver->has_javascript) { ...; }
  1152. =cut
  1153. sub has_javascript {
  1154. my $self = shift;
  1155. return int($self->javascript);
  1156. }
  1157. =head2 execute_async_script
  1158. Description:
  1159. Inject a snippet of JavaScript into the page for execution in the context
  1160. of the currently selected frame. The executed script is assumed to be
  1161. asynchronous and must signal that is done by invoking the provided
  1162. callback, which is always provided as the final argument to the function.
  1163. The value to this callback will be returned to the client.
  1164. Asynchronous script commands may not span page loads. If an unload event
  1165. is fired while waiting for a script result, an error should be returned
  1166. to the client.
  1167. Input: 2 (1 optional)
  1168. Required:
  1169. STRING - Javascript to execute on the page
  1170. Optional:
  1171. ARRAY - list of arguments that need to be passed to the script.
  1172. Output:
  1173. {*} - Varied, depending on the type of result expected back from the script.
  1174. Usage:
  1175. my $script = q{
  1176. var arg1 = arguments[0];
  1177. var callback = arguments[arguments.length-1];
  1178. var elem = window.document.findElementById(arg1);
  1179. callback(elem);
  1180. };
  1181. my $elem = $driver->execute_async_script($script,'myid');
  1182. $elem->click;
  1183. =cut
  1184. sub execute_async_script {
  1185. my ( $self, $script, @args ) = @_;
  1186. if ( $self->has_javascript ) {
  1187. if ( not defined $script ) {
  1188. croak 'No script provided';
  1189. }
  1190. my $res = { 'command' => 'executeAsyncScript' . $self->_execute_script_suffix};
  1191. # Check the args array if the elem obj is provided & replace it with
  1192. # JSON representation
  1193. for ( my $i = 0; $i < @args; $i++ ) {
  1194. if ( Scalar::Util::blessed( $args[$i] )
  1195. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1196. {
  1197. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1198. }
  1199. }
  1200. my $params = { 'script' => $script, 'args' => \@args };
  1201. my $ret = $self->_execute_command( $res, $params );
  1202. # replace any ELEMENTS with WebElement
  1203. if ( ref($ret)
  1204. and ( ref($ret) eq 'HASH' )
  1205. and $self->_looks_like_element($ret) )
  1206. {
  1207. $ret = $self->webelement_class->new(
  1208. id => $ret,
  1209. driver => $self
  1210. );
  1211. }
  1212. return $ret;
  1213. }
  1214. else {
  1215. croak 'Javascript is not enabled on remote driver instance.';
  1216. }
  1217. }
  1218. =head2 execute_script
  1219. Description:
  1220. Inject a snippet of JavaScript into the page and return its result.
  1221. WebElements that should be passed to the script as an argument should be
  1222. specified in the arguments array as WebElement object. Likewise,
  1223. any WebElements in the script result will be returned as WebElement object.
  1224. Input: 2 (1 optional)
  1225. Required:
  1226. STRING - Javascript to execute on the page
  1227. Optional:
  1228. ARRAY - list of arguments that need to be passed to the script.
  1229. Output:
  1230. {*} - Varied, depending on the type of result expected back from the script.
  1231. Usage:
  1232. my $script = q{
  1233. var arg1 = arguments[0];
  1234. var elem = window.document.findElementById(arg1);
  1235. return elem;
  1236. };
  1237. my $elem = $driver->execute_script($script,'myid');
  1238. $elem->click;
  1239. =cut
  1240. sub execute_script {
  1241. my ( $self, $script, @args ) = @_;
  1242. if ( $self->has_javascript ) {
  1243. if ( not defined $script ) {
  1244. croak 'No script provided';
  1245. }
  1246. my $res = { 'command' => 'executeScript' . $self->_execute_script_suffix };
  1247. # Check the args array if the elem obj is provided & replace it with
  1248. # JSON representation
  1249. for ( my $i = 0; $i < @args; $i++ ) {
  1250. if ( Scalar::Util::blessed( $args[$i] )
  1251. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1252. {
  1253. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1254. }
  1255. }
  1256. my $params = { 'script' => $script, 'args' => [@args] };
  1257. my $ret = $self->_execute_command( $res, $params );
  1258. return $self->_convert_to_webelement($ret);
  1259. }
  1260. else {
  1261. croak 'Javascript is not enabled on remote driver instance.';
  1262. }
  1263. }
  1264. # _looks_like_element
  1265. # An internal method to check if a return value might be an element
  1266. sub _looks_like_element {
  1267. my ($self, $maybe_element) = @_;
  1268. return (exists $maybe_element->{ELEMENT}
  1269. or exists $maybe_element->{'element-6066-11e4-a52e-4f735466cecf'});
  1270. }
  1271. # _convert_to_webelement
  1272. # An internal method used to traverse a data structure
  1273. # and convert any ELEMENTS with WebElements
  1274. sub _convert_to_webelement {
  1275. my ( $self, $ret ) = @_;
  1276. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  1277. if ( $self->_looks_like_element($ret) ) {
  1278. # replace an ELEMENT with WebElement
  1279. return $self->webelement_class->new(
  1280. id => $ret,
  1281. driver => $self
  1282. );
  1283. }
  1284. my %hash;
  1285. foreach my $key ( keys %$ret ) {
  1286. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1287. }
  1288. return \%hash;
  1289. }
  1290. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1291. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1292. return \@array;
  1293. }
  1294. return $ret;
  1295. }
  1296. =head2 screenshot
  1297. Description:
  1298. Get a screenshot of the current page as a base64 encoded image.
  1299. Output:
  1300. STRING - base64 encoded image
  1301. Usage:
  1302. print $driver->screenshot();
  1303. To conveniently write the screenshot to a file, see L</capture_screenshot>.
  1304. =cut
  1305. sub screenshot {
  1306. my ($self) = @_;
  1307. my $res = { 'command' => 'screenshot' };
  1308. return $self->_execute_command($res);
  1309. }
  1310. =head2 capture_screenshot
  1311. Description:
  1312. Capture a screenshot and save as a PNG to provided file name.
  1313. (The method is compatible with the WWW::Selenium method of the same name)
  1314. Output:
  1315. TRUE - (Screenshot is written to file)
  1316. Usage:
  1317. $driver->capture_screenshot($filename);
  1318. =cut
  1319. sub capture_screenshot {
  1320. my ( $self, $filename ) = @_;
  1321. croak '$filename is required' unless $filename;
  1322. open( my $fh, '>', $filename );
  1323. binmode $fh;
  1324. print $fh MIME::Base64::decode_base64( $self->screenshot() );
  1325. CORE::close $fh;
  1326. return 1;
  1327. }
  1328. =head2 available_engines
  1329. Description:
  1330. List all available engines on the machine. To use an engine, it has to be present in this list.
  1331. Output:
  1332. {Array.<string>} A list of available engines
  1333. Usage:
  1334. print Dumper $driver->available_engines;
  1335. =cut
  1336. sub available_engines {
  1337. my ($self) = @_;
  1338. my $res = { 'command' => 'availableEngines' };
  1339. return $self->_execute_command($res);
  1340. }
  1341. =head2 switch_to_frame
  1342. Description:
  1343. Change focus to another frame on the page. If the frame ID is null, the
  1344. server will switch to the page's default content. You can also switch to a
  1345. WebElement, for e.g. you can find an iframe using find_element & then
  1346. provide that as an input to this method. Also see e.g.
  1347. Input: 1
  1348. Required:
  1349. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1350. mentioned.
  1351. Usage:
  1352. $driver->switch_to_frame('frame_1');
  1353. or
  1354. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1355. =cut
  1356. sub switch_to_frame {
  1357. my ( $self, $id ) = @_;
  1358. my $json_null = JSON::null;
  1359. my $params;
  1360. $id = ( defined $id ) ? $id : $json_null;
  1361. my $res = { 'command' => 'switchToFrame' };
  1362. if ( ref $id eq $self->webelement_class ) {
  1363. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1364. }
  1365. else {
  1366. $params = { 'id' => $id };
  1367. }
  1368. return $self->_execute_command( $res, $params );
  1369. }
  1370. =head2 switch_to_window
  1371. Description:
  1372. Change focus to another window. The window to change focus to may
  1373. be specified by its server assigned window handle, or by the value
  1374. of the page's window.name attribute.
  1375. If you wish to use the window name as the target, you'll need to
  1376. have set C<window.name> on the page either in app code or via
  1377. L</execute_script>, or pass a name as the second argument to the
  1378. C<window.open()> function when opening the new window. Note that
  1379. the window name used here has nothing to do with the window title,
  1380. or the C<< <title> >> element on the page.
  1381. Otherwise, use L</get_window_handles> and select a
  1382. Webdriver-generated handle from the output of that function.
  1383. Input: 1
  1384. Required:
  1385. STRING - Window handle or the Window name
  1386. Usage:
  1387. $driver->switch_to_window('MY Homepage');
  1388. or
  1389. # close a popup window and switch back
  1390. my $handles = $driver->get_window_handles;
  1391. $driver->switch_to_window($handles->[1]);
  1392. $driver->close;
  1393. $driver->switch_to_window($handles->[0]);
  1394. =cut
  1395. sub switch_to_window {
  1396. my ( $self, $name ) = @_;
  1397. if ( not defined $name ) {
  1398. return 'Window name not provided';
  1399. }
  1400. my $res = { 'command' => 'switchToWindow' };
  1401. my $params = { 'name' => $name, 'handle' => $name };
  1402. return $self->_execute_command( $res, $params );
  1403. }
  1404. =head2 set_window_position
  1405. Description:
  1406. Set the position (on screen) where you want your browser to be displayed.
  1407. Input:
  1408. INT - x co-ordinate
  1409. INT - y co-ordinate
  1410. STRING - <optional> - window handle (default is 'current' window)
  1411. Output:
  1412. BOOLEAN - Success or failure
  1413. Usage:
  1414. $driver->set_window_position(50, 50);
  1415. =cut
  1416. sub set_window_position {
  1417. my ( $self, $x, $y, $window ) = @_;
  1418. $window = ( defined $window ) ? $window : 'current';
  1419. if ( not defined $x and not defined $y ) {
  1420. croak "X & Y co-ordinates are required";
  1421. }
  1422. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1423. my $params = { 'x' => $x, 'y' => $y };
  1424. my $ret = $self->_execute_command( $res, $params );
  1425. return $ret ? 1 : 0;
  1426. }
  1427. =head2 set_window_size
  1428. Description:
  1429. Set the size of the browser window
  1430. Input:
  1431. INT - height of the window
  1432. INT - width of the window
  1433. STRING - <optional> - window handle (default is 'current' window)
  1434. Output:
  1435. BOOLEAN - Success or failure
  1436. Usage:
  1437. $driver->set_window_size(640, 480);
  1438. =cut
  1439. sub set_window_size {
  1440. my ( $self, $height, $width, $window ) = @_;
  1441. $window = ( defined $window ) ? $window : 'current';
  1442. if ( not defined $height and not defined $width ) {
  1443. croak "height & width of browser are required";
  1444. }
  1445. $height += 0;
  1446. $width += 0;
  1447. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1448. my $params = { 'height' => $height, 'width' => $width };
  1449. my $ret = $self->_execute_command( $res, $params );
  1450. return $ret ? 1 : 0;
  1451. }
  1452. =head2 maximize_window
  1453. Description:
  1454. Maximizes the browser window
  1455. Input:
  1456. STRING - <optional> - window handle (default is 'current' window)
  1457. Output:
  1458. BOOLEAN - Success or failure
  1459. Usage:
  1460. $driver->maximize_window();
  1461. =cut
  1462. sub maximize_window {
  1463. my ( $self, $window ) = @_;
  1464. $window = ( defined $window ) ? $window : 'current';
  1465. my $res = { 'command' => 'maximizeWindow', 'window_handle' => $window };
  1466. my $ret = $self->_execute_command( $res );
  1467. return $ret ? 1 : 0;
  1468. }
  1469. =head2 get_all_cookies
  1470. Description:
  1471. Retrieve all cookies visible to the current page. Each cookie will be
  1472. returned as a HASH reference with the following keys & their value types:
  1473. 'name' - STRING
  1474. 'value' - STRING
  1475. 'path' - STRING
  1476. 'domain' - STRING
  1477. 'secure' - BOOLEAN
  1478. Output:
  1479. ARRAY of HASHES - list of all the cookie hashes
  1480. Usage:
  1481. print Dumper($driver->get_all_cookies());
  1482. =cut
  1483. sub get_all_cookies {
  1484. my ($self) = @_;
  1485. my $res = { 'command' => 'getAllCookies' };
  1486. return $self->_execute_command($res);
  1487. }
  1488. =head2 add_cookie
  1489. Description:
  1490. Set a cookie on the domain.
  1491. Input: 5 (1 optional)
  1492. Required:
  1493. 'name' - STRING
  1494. 'value' - STRING
  1495. 'path' - STRING
  1496. 'domain' - STRING
  1497. Optional:
  1498. 'secure' - BOOLEAN - default is false.
  1499. Usage:
  1500. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1501. =cut
  1502. sub add_cookie {
  1503. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1504. if ( ( not defined $name )
  1505. || ( not defined $value )
  1506. || ( not defined $path )
  1507. || ( not defined $domain ) )
  1508. {
  1509. croak "Missing parameters";
  1510. }
  1511. my $res = { 'command' => 'addCookie' };
  1512. my $json_false = JSON::false;
  1513. my $json_true = JSON::true;
  1514. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1515. my $params = {
  1516. 'cookie' => {
  1517. 'name' => $name,
  1518. 'value' => $value,
  1519. 'path' => $path,
  1520. 'domain' => $domain,
  1521. 'secure' => $secure,
  1522. }
  1523. };
  1524. return $self->_execute_command( $res, $params );
  1525. }
  1526. =head2 delete_all_cookies
  1527. Description:
  1528. Delete all cookies visible to the current page.
  1529. Usage:
  1530. $driver->delete_all_cookies();
  1531. =cut
  1532. sub delete_all_cookies {
  1533. my ($self) = @_;
  1534. my $res = { 'command' => 'deleteAllCookies' };
  1535. return $self->_execute_command($res);
  1536. }
  1537. =head2 delete_cookie_named
  1538. Description:
  1539. Delete the cookie with the given name. This command will be a no-op if there
  1540. is no such cookie visible to the current page.
  1541. Input: 1
  1542. Required:
  1543. STRING - name of cookie to delete
  1544. Usage:
  1545. $driver->delete_cookie_named('foo');
  1546. =cut
  1547. sub delete_cookie_named {
  1548. my ( $self, $cookie_name ) = @_;
  1549. if ( not defined $cookie_name ) {
  1550. croak "Cookie name not provided";
  1551. }
  1552. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1553. return $self->_execute_command($res);
  1554. }
  1555. =head2 get_page_source
  1556. Description:
  1557. Get the current page source.
  1558. Output:
  1559. STRING - The page source.
  1560. Usage:
  1561. print $driver->get_page_source();
  1562. =cut
  1563. sub get_page_source {
  1564. my ($self) = @_;
  1565. my $res = { 'command' => 'getPageSource' };
  1566. return $self->_execute_command($res);
  1567. }
  1568. =head2 find_element
  1569. Description:
  1570. Search for an element on the page, starting from the document
  1571. root. The located element will be returned as a WebElement
  1572. object. If the element cannot be found, we will CROAK, killing
  1573. your script. If you wish for a warning instead, use the
  1574. parameterized version of the finders:
  1575. find_element_by_class
  1576. find_element_by_class_name
  1577. find_element_by_css
  1578. find_element_by_id
  1579. find_element_by_link
  1580. find_element_by_link_text
  1581. find_element_by_name
  1582. find_element_by_partial_link_text
  1583. find_element_by_tag_name
  1584. find_element_by_xpath
  1585. These functions all take a single STRING argument: the locator
  1586. search target of the element you want. If the element is found, we
  1587. will receive a WebElement. Otherwise, we will return 0. Note that
  1588. invoking methods on 0 will of course kill your script.
  1589. Input: 2 (1 optional)
  1590. Required:
  1591. STRING - The search target.
  1592. Optional:
  1593. STRING - Locator scheme to use to search the element, available schemes:
  1594. {class, class_name, css, id, link, link_text, partial_link_text,
  1595. tag_name, name, xpath}
  1596. Defaults to 'xpath' if not configured global during instantiation.
  1597. Output:
  1598. Selenium::Remote::WebElement - WebElement Object
  1599. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1600. Usage:
  1601. $driver->find_element("//input[\@name='q']");
  1602. =cut
  1603. sub find_element {
  1604. my ( $self, $query, $method ) = @_;
  1605. if ( not defined $query ) {
  1606. croak 'Search string to find element not provided.';
  1607. }
  1608. my $res = { 'command' => 'findElement' };
  1609. my $params = $self->_build_find_params($method, $query);
  1610. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1611. if ($@) {
  1612. if ( $@
  1613. =~ /(An element could not be located on the page using the given search parameters)/
  1614. ) {
  1615. # give details on what element wasn't found
  1616. $@ = "$1: $query,$params->{using}";
  1617. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1618. croak $@;
  1619. }
  1620. else {
  1621. # re throw if the exception wasn't what we expected
  1622. die $@;
  1623. }
  1624. }
  1625. return $self->webelement_class->new(
  1626. id => $ret_data,
  1627. driver => $self
  1628. );
  1629. }
  1630. =head2 find_elements
  1631. Description:
  1632. Search for multiple elements on the page, starting from the document root.
  1633. The located elements will be returned as an array of WebElement object.
  1634. Input: 2 (1 optional)
  1635. Required:
  1636. STRING - The search target.
  1637. Optional:
  1638. STRING - Locator scheme to use to search the element, available schemes:
  1639. {class, class_name, css, id, link, link_text, partial_link_text,
  1640. tag_name, name, xpath}
  1641. Defaults to 'xpath' if not configured global during instantiation.
  1642. Output:
  1643. ARRAY or ARRAYREF of WebElement Objects
  1644. Usage:
  1645. $driver->find_elements("//input");
  1646. =cut
  1647. sub find_elements {
  1648. my ( $self, $query, $method ) = @_;
  1649. if ( not defined $query ) {
  1650. croak 'Search string to find element not provided.';
  1651. }
  1652. my $res = { 'command' => 'findElements' };
  1653. my $params = $self->_build_find_params($method, $query);
  1654. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1655. if ($@) {
  1656. if ( $@
  1657. =~ /(An element could not be located on the page using the given search parameters)/
  1658. ) {
  1659. # give details on what element wasn't found
  1660. $@ = "$1: $query,$params->{using}";
  1661. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1662. croak $@;
  1663. }
  1664. else {
  1665. # re throw if the exception wasn't what we expected
  1666. die $@;
  1667. }
  1668. }
  1669. my $elem_obj_arr = [];
  1670. foreach (@$ret_data) {
  1671. push(
  1672. @$elem_obj_arr,
  1673. $self->webelement_class->new(
  1674. id => $_,
  1675. driver => $self
  1676. )
  1677. );
  1678. }
  1679. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1680. }
  1681. =head2 find_child_element
  1682. Description:
  1683. Search for an element on the page, starting from the identified element. The
  1684. located element will be returned as a WebElement object.
  1685. Input: 3 (1 optional)
  1686. Required:
  1687. Selenium::Remote::WebElement - WebElement object from where you want to
  1688. start searching.
  1689. STRING - The search target. (Do not use a double whack('//')
  1690. in an xpath to search for a child element
  1691. ex: '//option[@id="something"]'
  1692. instead use a dot whack ('./')
  1693. ex: './option[@id="something"]')
  1694. Optional:
  1695. STRING - Locator scheme to use to search the element, available schemes:
  1696. {class, class_name, css, id, link, link_text, partial_link_text,
  1697. tag_name, name, xpath}
  1698. Defaults to 'xpath' if not configured global during instantiation.
  1699. Output:
  1700. WebElement Object
  1701. Usage:
  1702. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1703. # note the usage of ./ when searching for a child element instead of //
  1704. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1705. =cut
  1706. sub find_child_element {
  1707. my ( $self, $elem, $query, $method ) = @_;
  1708. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1709. croak "Missing parameters";
  1710. }
  1711. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1712. my $params = $self->_build_find_params($method, $query);
  1713. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1714. if ($@) {
  1715. if ( $@
  1716. =~ /(An element could not be located on the page using the given search parameters)/
  1717. ) {
  1718. # give details on what element wasn't found
  1719. $@ = "$1: $query,$params->{using}";
  1720. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1721. croak $@;
  1722. }
  1723. else {
  1724. # re throw if the exception wasn't what we expected
  1725. die $@;
  1726. }
  1727. }
  1728. return $self->webelement_class->new(
  1729. id => $ret_data,
  1730. driver => $self
  1731. );
  1732. }
  1733. =head2 find_child_elements
  1734. Description:
  1735. Search for multiple element on the page, starting from the identified
  1736. element. The located elements will be returned as an array of WebElement
  1737. objects.
  1738. Input: 3 (1 optional)
  1739. Required:
  1740. Selenium::Remote::WebElement - WebElement object from where you want to
  1741. start searching.
  1742. STRING - The search target.
  1743. Optional:
  1744. STRING - Locator scheme to use to search the element, available schemes:
  1745. {class, class_name, css, id, link, link_text, partial_link_text,
  1746. tag_name, name, xpath}
  1747. Defaults to 'xpath' if not configured global during instantiation.
  1748. Output:
  1749. ARRAY of WebElement Objects.
  1750. Usage:
  1751. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1752. # note the usage of ./ when searching for a child element instead of //
  1753. my $child = $driver->find_child_elements($elem1, "./option");
  1754. =cut
  1755. sub find_child_elements {
  1756. my ( $self, $elem, $query, $method ) = @_;
  1757. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1758. croak "Missing parameters";
  1759. }
  1760. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1761. my $params = $self->_build_find_params($method, $query);
  1762. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1763. if ($@) {
  1764. if ( $@
  1765. =~ /(An element could not be located on the page using the given search parameters)/
  1766. ) {
  1767. # give details on what element wasn't found
  1768. $@ = "$1: $query,$params->{using}";
  1769. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1770. croak $@;
  1771. }
  1772. else {
  1773. # re throw if the exception wasn't what we expected
  1774. die $@;
  1775. }
  1776. }
  1777. my $elem_obj_arr = [];
  1778. my $i = 0;
  1779. foreach (@$ret_data) {
  1780. $elem_obj_arr->[$i] =
  1781. $self->webelement_class->new(
  1782. id => $_,
  1783. driver => $self
  1784. );
  1785. $i++;
  1786. }
  1787. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1788. }
  1789. =head2 find_element_by_class
  1790. See L</find_element>.
  1791. =head2 find_element_by_class_name
  1792. See L</find_element>.
  1793. =head2 find_element_by_css
  1794. See L</find_element>.
  1795. =head2 find_element_by_id
  1796. See L</find_element>.
  1797. =head2 find_element_by_link
  1798. See L</find_element>.
  1799. =head2 find_element_by_link_text
  1800. See L</find_element>.
  1801. =head2 find_element_by_name
  1802. See L</find_element>.
  1803. =head2 find_element_by_partial_link_text
  1804. See L</find_element>.
  1805. =head2 find_element_by_tag_name
  1806. See L</find_element>.
  1807. =head2 find_element_by_xpath
  1808. See L</find_element>.
  1809. =head2 get_active_element
  1810. Description:
  1811. Get the element on the page that currently has focus.. The located element
  1812. will be returned as a WebElement object.
  1813. Output:
  1814. WebElement Object
  1815. Usage:
  1816. $driver->get_active_element();
  1817. =cut
  1818. sub _build_find_params {
  1819. my ($self, $method, $query) = @_;
  1820. my $using = $self->_build_using($method);
  1821. # geckodriver doesn't accept name as a valid selector
  1822. if ($self->isa('Selenium::Firefox') && $using eq 'name') {
  1823. return {
  1824. using => 'css',
  1825. value => '[name=$query]'
  1826. };
  1827. }
  1828. else {
  1829. return {
  1830. using => $using,
  1831. value => $query
  1832. };
  1833. }
  1834. }
  1835. sub _build_using {
  1836. my ($self, $method) = @_;
  1837. if ($method) {
  1838. if ($self->FINDERS->{$method}) {
  1839. return $self->FINDERS->{$method};
  1840. }
  1841. else {
  1842. croak 'Bad method, expected: ' . join(', ', keys %{ $self->FINDERS });
  1843. }
  1844. }
  1845. else {
  1846. return $self->default_finder;
  1847. }
  1848. }
  1849. sub get_active_element {
  1850. my ($self) = @_;
  1851. my $res = { 'command' => 'getActiveElement' };
  1852. my $ret_data = eval { $self->_execute_command($res) };
  1853. if ($@) {
  1854. croak $@;
  1855. }
  1856. else {
  1857. return $self->webelement_class->new(
  1858. id => $ret_data,
  1859. driver => $self
  1860. );
  1861. }
  1862. }
  1863. =head2 cache_status
  1864. Description:
  1865. Get the status of the html5 application cache.
  1866. Usage:
  1867. print $driver->cache_status;
  1868. Output:
  1869. <number> - Status code for application cache: {UNCACHED = 0, IDLE = 1, CHECKING = 2, DOWNLOADING = 3, UPDATE_READY = 4, OBSOLETE = 5}
  1870. =cut
  1871. sub cache_status {
  1872. my ($self) = @_;
  1873. my $res = { 'command' => 'cacheStatus' };
  1874. return $self->_execute_command($res);
  1875. }
  1876. =head2 set_geolocation
  1877. Description:
  1878. Set the current geographic location - note that your driver must
  1879. implement this endpoint, or else it will crash your session. At the
  1880. very least, it works in v2.12 of Chromedriver.
  1881. Input:
  1882. Required:
  1883. HASH: A hash with key C<location> whose value is a Location hashref. See
  1884. usage section for example.
  1885. Usage:
  1886. $driver->set_geolocation( location => {
  1887. latitude => 40.714353,
  1888. longitude => -74.005973,
  1889. altitude => 0.056747
  1890. });
  1891. Output:
  1892. BOOLEAN - success or failure
  1893. =cut
  1894. sub set_geolocation {
  1895. my ( $self, %params ) = @_;
  1896. my $res = { 'command' => 'setGeolocation' };
  1897. return $self->_execute_command( $res, \%params );
  1898. }
  1899. =head2 get_geolocation
  1900. Description:
  1901. Get the current geographic location. Note that your webdriver must
  1902. implement this endpoint - otherwise, it will crash your session. At
  1903. the time of release, we couldn't get this to work on the desktop
  1904. FirefoxDriver or desktop Chromedriver.
  1905. Usage:
  1906. print $driver->get_geolocation;
  1907. Output:
  1908. { latitude: number, longitude: number, altitude: number } - The current geo location.
  1909. =cut
  1910. sub get_geolocation {
  1911. my ($self) = @_;
  1912. my $res = { 'command' => 'getGeolocation' };
  1913. return $self->_execute_command($res);
  1914. }
  1915. =head2 get_log
  1916. Description:
  1917. Get the log for a given log type. Log buffer is reset after each request.
  1918. Input:
  1919. Required:
  1920. <STRING> - Type of log to retrieve:
  1921. {client|driver|browser|server}. There may be others available; see
  1922. get_log_types for a full list for your driver.
  1923. Usage:
  1924. $driver->get_log( $log_type );
  1925. Output:
  1926. <ARRAY|ARRAYREF> - An array of log entries since the most recent request.
  1927. =cut
  1928. sub get_log {
  1929. my ( $self, $type ) = @_;
  1930. my $res = { 'command' => 'getLog' };
  1931. return $self->_execute_command( $res, { type => $type });
  1932. }
  1933. =head2 get_log_types
  1934. Description:
  1935. Get available log types. By default, every driver should have client,
  1936. driver, browser, and server types, but there may be more available,
  1937. depending on your driver.
  1938. Usage:
  1939. my @types = $driver->get_log_types;
  1940. $driver->get_log($types[0]);
  1941. Output:
  1942. <ARRAYREF> - The list of log types.
  1943. =cut
  1944. sub get_log_types {
  1945. my ($self) = @_;
  1946. my $res = { 'command' => 'getLogTypes' };
  1947. return $self->_execute_command($res);
  1948. }
  1949. =head2 set_orientation
  1950. Description:
  1951. Set the browser orientation.
  1952. Input:
  1953. Required:
  1954. <STRING> - Orientation {LANDSCAPE|PORTRAIT}
  1955. Usage:
  1956. $driver->set_orientation( $orientation );
  1957. Output:
  1958. BOOLEAN - success or failure
  1959. =cut
  1960. sub set_orientation {
  1961. my ( $self, $orientation ) = @_;
  1962. my $res = { 'command' => 'setOrientation' };
  1963. return $self->_execute_command( $res, { orientation => $orientation } );
  1964. }
  1965. =head2 get_orientation
  1966. Description:
  1967. Get the current browser orientation. Returns either LANDSCAPE|PORTRAIT.
  1968. Usage:
  1969. print $driver->get_orientation;
  1970. Output:
  1971. <STRING> - your orientation.
  1972. =cut
  1973. sub get_orientation {
  1974. my ($self) = @_;
  1975. my $res = { 'command' => 'getOrientation' };
  1976. return $self->_execute_command($res);
  1977. }
  1978. =head2 send_modifier
  1979. Description:
  1980. Send an event to the active element to depress or release a modifier key.
  1981. Input: 2
  1982. Required:
  1983. 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
  1984. isdown - Boolean/String - Whether to generate a key down or key up
  1985. Usage:
  1986. $driver->send_modifier('Alt','down');
  1987. $elem->send_keys('c');
  1988. $driver->send_modifier('Alt','up');
  1989. or
  1990. $driver->send_modifier('Alt',1);
  1991. $elem->send_keys('c');
  1992. $driver->send_modifier('Alt',0);
  1993. =cut
  1994. sub send_modifier {
  1995. my ( $self, $modifier, $isdown ) = @_;
  1996. if ( $isdown =~ /(down|up)/ ) {
  1997. $isdown = $isdown =~ /down/ ? 1 : 0;
  1998. }
  1999. my $res = { 'command' => 'sendModifier' };
  2000. my $params = {
  2001. value => $modifier,
  2002. isdown => $isdown
  2003. };
  2004. return $self->_execute_command( $res, $params );
  2005. }
  2006. =head2 compare_elements
  2007. Description:
  2008. Test if two element IDs refer to the same DOM element.
  2009. Input: 2
  2010. Required:
  2011. Selenium::Remote::WebElement - WebElement Object
  2012. Selenium::Remote::WebElement - WebElement Object
  2013. Output:
  2014. BOOLEAN
  2015. Usage:
  2016. $driver->compare_elements($elem_obj1, $elem_obj2);
  2017. =cut
  2018. sub compare_elements {
  2019. my ( $self, $elem1, $elem2 ) = @_;
  2020. my $res = {
  2021. 'command' => 'elementEquals',
  2022. 'id' => $elem1->{id},
  2023. 'other' => $elem2->{id}
  2024. };
  2025. return $self->_execute_command($res);
  2026. }
  2027. =head2 click
  2028. Description:
  2029. Click any mouse button (at the coordinates set by the last moveto command).
  2030. Input:
  2031. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  2032. defaults to 'LEFT'
  2033. Usage:
  2034. $driver->click('LEFT');
  2035. $driver->click(1); #MIDDLE
  2036. $driver->click('RIGHT');
  2037. $driver->click; #Defaults to left
  2038. =cut
  2039. sub click {
  2040. my ( $self, $button ) = @_;
  2041. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  2042. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  2043. $button = $button_enum->{ uc $1 };
  2044. }
  2045. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  2046. $button = $1;
  2047. }
  2048. else {
  2049. $button = 0;
  2050. }
  2051. my $res = { 'command' => 'click' };
  2052. my $params = { 'button' => $button };
  2053. return $self->_execute_command( $res, $params );
  2054. }
  2055. =head2 double_click
  2056. Description:
  2057. Double-clicks at the current mouse coordinates (set by moveto).
  2058. Usage:
  2059. $driver->double_click;
  2060. =cut
  2061. sub double_click {
  2062. my ($self) = @_;
  2063. my $res = { 'command' => 'doubleClick' };
  2064. return $self->_execute_command($res);
  2065. }
  2066. =head2 button_down
  2067. Description:
  2068. Click and hold the left mouse button (at the coordinates set by the
  2069. last moveto command). Note that the next mouse-related command that
  2070. should follow is buttonup . Any other mouse command (such as click
  2071. or another call to buttondown) will yield undefined behaviour.
  2072. Usage:
  2073. $self->button_down;
  2074. =cut
  2075. sub button_down {
  2076. my ($self) = @_;
  2077. my $res = { 'command' => 'buttonDown' };
  2078. return $self->_execute_command($res);
  2079. }
  2080. =head2 button_up
  2081. Description:
  2082. Releases the mouse button previously held (where the mouse is
  2083. currently at). Must be called once for every buttondown command
  2084. issued. See the note in click and buttondown about implications of
  2085. out-of-order commands.
  2086. Usage:
  2087. $self->button_up;
  2088. =cut
  2089. sub button_up {
  2090. my ($self) = @_;
  2091. my $res = { 'command' => 'buttonUp' };
  2092. return $self->_execute_command($res);
  2093. }
  2094. =head2 upload_file
  2095. Description:
  2096. Upload a file from the local machine to the selenium server
  2097. machine. That file then can be used for testing file upload on web
  2098. forms. Returns the remote-server's path to the file.
  2099. Passing raw data as an argument past the filename will upload
  2100. that rather than the file's contents.
  2101. When passing raw data, be advised that it expects a zipped
  2102. and then base64 encoded version of a single file.
  2103. Multiple files and/or directories are not supported by the remote server.
  2104. Usage:
  2105. my $remote_fname = $driver->upload_file( $fname );
  2106. my $element = $driver->find_element( '//input[@id="file"]' );
  2107. $element->send_keys( $remote_fname );
  2108. =cut
  2109. # this method duplicates upload() method in the
  2110. # org.openqa.selenium.remote.RemoteWebElement java class.
  2111. sub upload_file {
  2112. my ( $self, $filename, $raw_content ) = @_;
  2113. my $params;
  2114. if (defined $raw_content) {
  2115. #If no processing is passed, send the argument raw
  2116. $params = {
  2117. file => $raw_content
  2118. };
  2119. }
  2120. else {
  2121. #Otherwise, zip/base64 it.
  2122. $params = $self->_prepare_file($filename);
  2123. }
  2124. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  2125. my $ret = $self->_execute_command( $res, $params );
  2126. return $ret;
  2127. }
  2128. sub _prepare_file {
  2129. my ($self,$filename) = @_;
  2130. if ( not -r $filename ) { croak "upload_file: no such file: $filename"; }
  2131. my $string = ""; # buffer
  2132. my $zip = Archive::Zip->new();
  2133. $zip->addFile($filename, basename($filename));
  2134. if ($zip->writeToFileHandle(IO::String->new($string)) != AZ_OK) {
  2135. die 'zip failed';
  2136. }
  2137. return {
  2138. file => MIME::Base64::encode_base64($string, '')
  2139. };
  2140. }
  2141. =head2 get_text
  2142. Description:
  2143. Get the text of a particular element. Wrapper around L<find_element()>
  2144. Usage:
  2145. $text = $driver->get_text("//div[\@name='q']");
  2146. =cut
  2147. sub get_text {
  2148. my $self = shift;
  2149. return $self->find_element(@_)->get_text();
  2150. }
  2151. =head2 get_body
  2152. Description:
  2153. Get the current text for the whole body. If you want the entire raw HTML instead,
  2154. See L<get_page_source>.
  2155. Usage:
  2156. $body_text = $driver->get_body();
  2157. =cut
  2158. sub get_body {
  2159. my $self = shift;
  2160. return $self->get_text('//body', 'xpath');
  2161. }
  2162. =head2 get_path
  2163. Description:
  2164. Get the path part of the current browser location.
  2165. Usage:
  2166. $path = $driver->get_path();
  2167. =cut
  2168. sub get_path {
  2169. my $self = shift;
  2170. my $location = $self->get_current_url;
  2171. $location =~ s/\?.*//; # strip of query params
  2172. $location =~ s/#.*//; # strip of anchors
  2173. $location =~ s#^https?://[^/]+##; # strip off host
  2174. return $location;
  2175. }
  2176. =head2 get_user_agent
  2177. Description:
  2178. Convenience method to get the user agent string, according to the
  2179. browser's value for window.navigator.userAgent.
  2180. Usage:
  2181. $user_agent = $driver->get_user_agent()
  2182. =cut
  2183. sub get_user_agent {
  2184. my $self = shift;
  2185. return $self->execute_script('return window.navigator.userAgent;');
  2186. }
  2187. =head2 set_inner_window_size
  2188. Description:
  2189. Set the inner window size by closing the current window and
  2190. reopening the current page in a new window. This can be useful
  2191. when using browsers to mock as mobile devices.
  2192. This sub will be fired automatically if you set the
  2193. C<inner_window_size> hash key option during instantiation.
  2194. Input:
  2195. INT - height of the window
  2196. INT - width of the window
  2197. Output:
  2198. BOOLEAN - Success or failure
  2199. Usage:
  2200. $driver->set_inner_window_size(640, 480)
  2201. =cut
  2202. sub set_inner_window_size {
  2203. my $self = shift;
  2204. my $height = shift;
  2205. my $width = shift;
  2206. my $location = $self->get_current_url;
  2207. $self->execute_script('window.open("' . $location . '", "_blank")');
  2208. $self->close;
  2209. my @handles = @{ $self->get_window_handles };
  2210. $self->switch_to_window(pop @handles);
  2211. my @resize = (
  2212. 'window.innerHeight = ' . $height,
  2213. 'window.innerWidth = ' . $width,
  2214. 'return 1'
  2215. );
  2216. return $self->execute_script(join(';', @resize)) ? 1 : 0;
  2217. }
  2218. =head2 get_local_storage_item
  2219. Description:
  2220. Get the value of a local storage item specified by the given key.
  2221. Input: 1
  2222. Required:
  2223. STRING - name of the key to be retrieved
  2224. Output:
  2225. STRING - value of the local storage item
  2226. Usage:
  2227. $driver->get_local_storage_item('key')
  2228. =cut
  2229. sub get_local_storage_item {
  2230. my ($self, $key) = @_;
  2231. my $res = { 'command' => 'getLocalStorageItem' };
  2232. my $params = { 'key' => $key };
  2233. return $self->_execute_command($res, $params);
  2234. }
  2235. =head2 delete_local_storage_item
  2236. Description:
  2237. Get the value of a local storage item specified by the given key.
  2238. Input: 1
  2239. Required
  2240. STRING - name of the key to be deleted
  2241. Usage:
  2242. $driver->delete_local_storage_item('key')
  2243. =cut
  2244. sub delete_local_storage_item {
  2245. my ($self, $key) = @_;
  2246. my $res = { 'command' => 'deleteLocalStorageItem' };
  2247. my $params = { 'key' => $key };
  2248. return $self->_execute_command($res, $params);
  2249. }
  2250. sub _coerce_timeout_ms {
  2251. my ($ms) = @_;
  2252. if ( defined $ms ) {
  2253. return _coerce_number( $ms );
  2254. }
  2255. else {
  2256. croak 'Expecting a timeout in ms';
  2257. }
  2258. }
  2259. sub _coerce_number {
  2260. my ($maybe_number) = @_;
  2261. if ( Scalar::Util::looks_like_number( $maybe_number )) {
  2262. return $maybe_number + 0;
  2263. }
  2264. else {
  2265. croak "Expecting a number, not: $maybe_number";
  2266. }
  2267. }
  2268. 1;
  2269. __END__
  2270. =head1 SEE ALSO
  2271. http://code.google.com/p/selenium/
  2272. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  2273. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  2274. Brownie
  2275. Wight
  2276. =cut