1
0

Driver.pm 99 KB

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