Driver.pm 106 KB

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