1
0

Driver.pm 101 KB

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