Driver.pm 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708
  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. Use the option goog:chromeOptions instead of chromeOptions, if you are intending to pass extra_capabilities on a
  173. WD3 enabled server with chromedriver enabled.
  174. https://sites.google.com/a/chromium.org/chromedriver/capabilities
  175. Also, if you instantiate the object in WC3 mode (which is the default), the remote driver will throw exceptions you have no choice but to catch,
  176. rather than falling back to JSONWire methods where applicable like geckodriver does.
  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. 'goog: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. my $args = {
  671. 'desiredCapabilities' => {
  672. 'browserName' => $self->browser_name,
  673. 'platform' => $self->platform,
  674. 'javascriptEnabled' => $self->javascript,
  675. 'version' => $self->version,
  676. 'acceptSslCerts' => $self->accept_ssl_certs,
  677. %$extra_capabilities,
  678. },
  679. };
  680. $args->{'extra_capabilities'} = \%$extra_capabilities unless $FORCE_WD2;
  681. if ( defined $self->proxy ) {
  682. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  683. }
  684. if ( $args->{desiredCapabilities}->{browserName} =~ /firefox/i
  685. && $self->has_firefox_profile )
  686. {
  687. $args->{desiredCapabilities}->{firefox_profile} =
  688. $self->firefox_profile->_encode;
  689. }
  690. $self->_request_new_session($args);
  691. }
  692. =head2 new_desired_session(capabilities)
  693. Basically the same as new_session, but with caps.
  694. Sort of an analog to new_from_caps.
  695. =cut
  696. sub new_desired_session {
  697. my ( $self, $caps ) = @_;
  698. $self->_request_new_session(
  699. {
  700. desiredCapabilities => $caps
  701. }
  702. );
  703. }
  704. sub _request_new_session {
  705. my ( $self, $args ) = @_;
  706. #XXX UGLY shim for webdriver3
  707. $args->{capabilities}->{alwaysMatch} =
  708. clone( $args->{desiredCapabilities} );
  709. my $cmap = $self->commands_v3->get_caps_map();
  710. my $caps = $self->commands_v3->get_caps();
  711. foreach my $cap ( keys( %{ $args->{capabilities}->{alwaysMatch} } ) ) {
  712. #Handle browser specific capabilities
  713. if ( exists( $args->{desiredCapabilities}->{browserName} )
  714. && $cap eq 'extra_capabilities' )
  715. {
  716. if (
  717. exists $args->{capabilities}->{alwaysMatch}
  718. ->{'moz:firefoxOptions'}->{args} )
  719. {
  720. $args->{capabilities}->{alwaysMatch}->{$cap}->{args} =
  721. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  722. ->{args};
  723. }
  724. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'} =
  725. $args->{capabilities}->{alwaysMatch}->{$cap}
  726. if $args->{desiredCapabilities}->{browserName} eq 'firefox';
  727. #XXX the chrome documentation is lies, you can't do this yet
  728. #$args->{capabilities}->{alwaysMatch}->{'goog:chromeOptions'} = $args->{capabilities}->{alwaysMatch}->{$cap} if $args->{desiredCapabilities}->{browserName} eq 'chrome';
  729. #Does not appear there are any MSIE based options, so let's just let that be
  730. }
  731. if ( exists( $args->{desiredCapabilities}->{browserName} )
  732. && $args->{desiredCapabilities}->{browserName} eq 'firefox'
  733. && $cap eq 'firefox_profile' )
  734. {
  735. if (
  736. ref $args->{capabilities}->{alwaysMatch}->{$cap} eq
  737. 'Selenium::Firefox::Profile' )
  738. {
  739. #XXX not sure if I need to keep a ref to the File::Temp::Tempdir object to prevent reaping
  740. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  741. ->{args} = [
  742. '-profile',
  743. $args->{capabilities}->{alwaysMatch}->{$cap}->{profile_dir}
  744. ->dirname()
  745. ];
  746. }
  747. else {
  748. #previously undocumented feature that we can pass the encoded profile
  749. $args->{capabilities}->{alwaysMatch}->{'moz:firefoxOptions'}
  750. ->{profile} = $args->{capabilities}->{alwaysMatch}->{$cap};
  751. }
  752. }
  753. foreach my $newkey ( keys(%$cmap) ) {
  754. if ( $newkey eq $cap ) {
  755. last if $cmap->{$newkey} eq $cap;
  756. $args->{capabilities}->{alwaysMatch}->{ $cmap->{$newkey} } =
  757. $args->{capabilities}->{alwaysMatch}->{$cap};
  758. delete $args->{capabilities}->{alwaysMatch}->{$cap};
  759. last;
  760. }
  761. }
  762. delete $args->{capabilities}->{alwaysMatch}->{$cap}
  763. if !any { $_ eq $cap } @$caps;
  764. }
  765. delete $args->{desiredCapabilities}
  766. if $FORCE_WD3; #XXX fork working-around busted fallback in firefox
  767. delete $args->{capabilities}
  768. if $FORCE_WD2; #XXX 'secret' feature to help the legacy unit tests to work
  769. #Delete compatibility layer when using drivers directly
  770. if ( $self->isa('Selenium::Firefox') || $self->isa('Selenium::Chrome') ) {
  771. if ( exists $args->{capabilities}
  772. && exists $args->{capabilities}->{alwaysMatch} )
  773. {
  774. delete $args->{capabilities}->{alwaysMatch}->{browserName};
  775. delete $args->{capabilities}->{alwaysMatch}->{browserVersion};
  776. delete $args->{capabilities}->{alwaysMatch}->{platformName};
  777. }
  778. }
  779. #Fix broken out of the box chrome because they hate the maintainers of their interfaces
  780. if ( $self->isa('Selenium::Chrome') ) {
  781. if ( exists $args->{desiredCapabilities} ) {
  782. $args->{desiredCapabilities}{'goog:chromeOptions'}{args} //= [];
  783. push(@{$args->{desiredCapabilities}{'goog:chromeOptions'}{args}}, qw{no-sandbox disable-dev-shm-usage});
  784. }
  785. }
  786. # Get actual status
  787. $self->remote_conn->check_status();
  788. # command => 'newSession' to fool the tests of commands implemented
  789. # TODO: rewrite the testing better, this is so fragile.
  790. my $resource_new_session = {
  791. method => $self->commands->get_method('newSession'),
  792. url => $self->commands->get_url('newSession'),
  793. no_content_success =>
  794. $self->commands->get_no_content_success('newSession'),
  795. };
  796. my $rc = $self->remote_conn;
  797. my $resp = $rc->request( $resource_new_session, $args, );
  798. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'NOT OK' ) {
  799. croak "Could not obtain new session: ". $resp->{cmd_return}{message};
  800. }
  801. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  802. $self->session_id( $resp->{'sessionId'} );
  803. }
  804. else {
  805. my $error = 'Could not create new session';
  806. if ( ref $resp->{cmd_return} eq 'HASH' ) {
  807. $error .= ': ' . $resp->{cmd_return}->{message};
  808. }
  809. else {
  810. $error .= ': ' . $resp->{cmd_return};
  811. }
  812. croak $error;
  813. }
  814. #Webdriver 3 - best guess that this is 'whats goin on'
  815. if ( ref $resp->{cmd_return} eq 'HASH'
  816. && $resp->{cmd_return}->{capabilities} )
  817. {
  818. $self->{is_wd3} = 1;
  819. $self->{emulate_jsonwire} = 1;
  820. $self->{capabilities} = $resp->{cmd_return}->{capabilities};
  821. }
  822. #XXX chromedriver DOES NOT FOLLOW SPEC!
  823. if ( ref $resp->{cmd_return} eq 'HASH' && $resp->{cmd_return}->{chrome} ) {
  824. if ( defined $resp->{cmd_return}->{setWindowRect} )
  825. { #XXX i'm inferring we are wd3 based on the presence of this
  826. $self->{is_wd3} = 1;
  827. $self->{emulate_jsonwire} = 1;
  828. $self->{capabilities} = $resp->{cmd_return};
  829. }
  830. }
  831. #XXX unsurprisingly, neither does microsoft
  832. if ( ref $resp->{cmd_return} eq 'HASH'
  833. && $resp->{cmd_return}->{pageLoadStrategy}
  834. && $self->browser_name eq 'MicrosoftEdge' )
  835. {
  836. $self->{is_wd3} = 1;
  837. $self->{emulate_jsonwire} = 1;
  838. $self->{capabilities} = $resp->{cmd_return};
  839. }
  840. return ( $args, $resp );
  841. }
  842. =head2 is_webdriver_3
  843. Print whether the server (or browser) thinks it's implemented webdriver 3.
  844. 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.
  845. 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.
  846. Note how I said *thinks* above. In the case you want to force usage of legacy methods, set $driver->{is_wd3} to work around various browser issues.
  847. =cut
  848. sub is_webdriver_3 {
  849. my $self = shift;
  850. return $self->{is_wd3};
  851. }
  852. =head2 debug_on
  853. Description:
  854. Turns on debugging mode and the driver will print extra info like request
  855. and response to stdout. Useful, when you want to see what is being sent to
  856. the server & what response you are getting back.
  857. Usage:
  858. $driver->debug_on;
  859. =cut
  860. sub debug_on {
  861. my ($self) = @_;
  862. $self->{debug} = 1;
  863. $self->remote_conn->debug(1);
  864. }
  865. =head2 debug_off
  866. Description:
  867. Turns off the debugging mode.
  868. Usage:
  869. $driver->debug_off;
  870. =cut
  871. sub debug_off {
  872. my ($self) = @_;
  873. $self->{debug} = 0;
  874. $self->remote_conn->debug(0);
  875. }
  876. =head2 get_sessions
  877. Description:
  878. Returns a list of the currently active sessions. Each session will be
  879. returned as an array of Hashes with the following keys:
  880. 'id' : The session ID
  881. 'capabilities: An object describing session's capabilities
  882. Output:
  883. Array of Hashes
  884. Usage:
  885. print Dumper $driver->get_sessions();
  886. =cut
  887. sub get_sessions {
  888. my ($self) = @_;
  889. my $res = { 'command' => 'getSessions' };
  890. return $self->_execute_command($res);
  891. }
  892. =head2 status
  893. Description:
  894. Query the server's current status. All server implementations
  895. should return two basic objects describing the server's current
  896. platform and when the server was built.
  897. Output:
  898. Hash ref
  899. Usage:
  900. print Dumper $driver->status;
  901. =cut
  902. sub status {
  903. my ($self) = @_;
  904. my $res = { 'command' => 'status' };
  905. return $self->_execute_command($res);
  906. }
  907. =head2 get_alert_text
  908. Description:
  909. Gets the text of the currently displayed JavaScript alert(), confirm()
  910. or prompt() dialog.
  911. Example
  912. my $string = $driver->get_alert_text;
  913. =cut
  914. sub get_alert_text {
  915. my ($self) = @_;
  916. my $res = { 'command' => 'getAlertText' };
  917. return $self->_execute_command($res);
  918. }
  919. =head2 send_keys_to_active_element
  920. Description:
  921. Send a sequence of key strokes to the active element. This command is
  922. similar to the send keys command in every aspect except the implicit
  923. termination: The modifiers are not released at the end of the call.
  924. Rather, the state of the modifier keys is kept between calls, so mouse
  925. interactions can be performed while modifier keys are depressed.
  926. Compatibility:
  927. On webdriver 3 servers, don't use this to send modifier keys; use send_modifier instead.
  928. Input: 1
  929. Required:
  930. {ARRAY | STRING} - Array of strings or a string.
  931. Usage:
  932. $driver->send_keys_to_active_element('abcd', 'efg');
  933. $driver->send_keys_to_active_element('hijk');
  934. or
  935. # include the WDKeys module
  936. use Selenium::Remote::WDKeys;
  937. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  938. =cut
  939. sub send_keys_to_active_element {
  940. my ( $self, @strings ) = @_;
  941. if ( $self->{is_wd3}
  942. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  943. {
  944. @strings = map { split( '', $_ ) } @strings;
  945. my @acts = map {
  946. (
  947. {
  948. type => 'keyDown',
  949. value => $_,
  950. },
  951. {
  952. type => 'keyUp',
  953. value => $_,
  954. }
  955. )
  956. } @strings;
  957. my $action = {
  958. actions => [
  959. {
  960. id => 'key',
  961. type => 'key',
  962. actions => \@acts,
  963. }
  964. ]
  965. };
  966. return $self->general_action(%$action);
  967. }
  968. my $res = { 'command' => 'sendKeysToActiveElement' };
  969. my $params = { 'value' => \@strings, };
  970. return $self->_execute_command( $res, $params );
  971. }
  972. =head2 send_keys_to_alert
  973. Synonymous with send_keys_to_prompt
  974. =cut
  975. sub send_keys_to_alert {
  976. return shift->send_keys_to_prompt(@_);
  977. }
  978. =head2 send_keys_to_prompt
  979. Description:
  980. Sends keystrokes to a JavaScript prompt() dialog.
  981. Input:
  982. {string} keys to send
  983. Example:
  984. $driver->send_keys_to_prompt('hello world');
  985. or
  986. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  987. $driver->send_keys_to_alert("Larry Wall");
  988. $driver->accept_alert;
  989. =cut
  990. sub send_keys_to_prompt {
  991. my ( $self, $keys ) = @_;
  992. my $res = { 'command' => 'sendKeysToPrompt' };
  993. my $params = { 'text' => $keys };
  994. return $self->_execute_command( $res, $params );
  995. }
  996. =head2 accept_alert
  997. Description:
  998. Accepts the currently displayed alert dialog. Usually, this is
  999. equivalent to clicking the 'OK' button in the dialog.
  1000. Example:
  1001. $driver->accept_alert;
  1002. =cut
  1003. sub accept_alert {
  1004. my ($self) = @_;
  1005. my $res = { 'command' => 'acceptAlert' };
  1006. return $self->_execute_command($res);
  1007. }
  1008. =head2 dismiss_alert
  1009. Description:
  1010. Dismisses the currently displayed alert dialog. For comfirm()
  1011. and prompt() dialogs, this is equivalent to clicking the
  1012. 'Cancel' button. For alert() dialogs, this is equivalent to
  1013. clicking the 'OK' button.
  1014. Example:
  1015. $driver->dismiss_alert;
  1016. =cut
  1017. sub dismiss_alert {
  1018. my ($self) = @_;
  1019. my $res = { 'command' => 'dismissAlert' };
  1020. return $self->_execute_command($res);
  1021. }
  1022. =head2 general_action
  1023. Provide an 'actions definition' hash to make webdriver use input devices.
  1024. Given the spec for the structure of this data is 'non normative',
  1025. it is left as an exercise to the reader what that means as to how to use this function.
  1026. That said, it seems most of the data looks something like this:
  1027. $driver->general_action( actions => [{
  1028. type => 'pointer|key|none|somethingElseSuperSpecialDefinedByYourBrowserDriver',
  1029. 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.
  1030. 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.
  1031. parameters => {
  1032. someOption => "basically these are global parameters used by all steps in the forthcoming "action chain".
  1033. },
  1034. actions => [
  1035. {
  1036. type => "keyUp|KeyDown if key, pointerUp|pointerDown|pointerMove|pointerCancel if pointer, pause if any type",
  1037. key => A raw keycode or character from the keyboard if this is a key event,
  1038. 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.
  1039. 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)
  1040. origin => Point of Origin if moving a pointer around
  1041. x => unit vector to travel along x-axis if pointerMove event
  1042. y => unit vector to travel along y-axis if pointerMove event
  1043. },
  1044. ...
  1045. ]
  1046. },
  1047. ...
  1048. ]
  1049. )
  1050. Only available on WebDriver3 capable selenium servers.
  1051. 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.
  1052. Called with no arguments, it simply executes the existing action queue.
  1053. If you are looking for pre-baked action chains that aren't currently part of L<Selenium::Remote::Driver>,
  1054. consider L<Selenium::ActionChains>, which is shipped with this distribution instead.
  1055. =cut
  1056. sub general_action {
  1057. my ( $self, %action ) = @_;
  1058. _queue_action(%action);
  1059. my $res = { 'command' => 'generalAction' };
  1060. my $out = $self->_execute_command( $res, \%CURRENT_ACTION_CHAIN );
  1061. %CURRENT_ACTION_CHAIN = ( actions => [] );
  1062. return $out;
  1063. }
  1064. sub _queue_action {
  1065. my (%action) = @_;
  1066. if ( ref $action{actions} eq 'ARRAY' ) {
  1067. foreach my $live_action ( @{ $action{actions} } ) {
  1068. my $existing_action;
  1069. foreach my $global_action ( @{ $CURRENT_ACTION_CHAIN{actions} } ) {
  1070. if ( $global_action->{id} eq $live_action->{id} ) {
  1071. $existing_action = $global_action;
  1072. last;
  1073. }
  1074. }
  1075. if ($existing_action) {
  1076. push(
  1077. @{ $existing_action->{actions} },
  1078. @{ $live_action->{actions} }
  1079. );
  1080. }
  1081. else {
  1082. push( @{ $CURRENT_ACTION_CHAIN{actions} }, $live_action );
  1083. }
  1084. }
  1085. }
  1086. }
  1087. =head2 release_general_action
  1088. Nukes *all* input device state (modifier key up/down, pointer button up/down, pointer location, and other device state) from orbit.
  1089. Call if you forget to do a *Up event in your provided action chains, or just to save time.
  1090. Also clears the current actions queue.
  1091. Only available on WebDriver3 capable selenium servers.
  1092. =cut
  1093. sub release_general_action {
  1094. my ($self) = @_;
  1095. my $res = { 'command' => 'releaseGeneralAction' };
  1096. %CURRENT_ACTION_CHAIN = ( actions => [] );
  1097. return $self->_execute_command($res);
  1098. }
  1099. =head2 mouse_move_to_location
  1100. Description:
  1101. Move the mouse by an offset of the specificed element. If no
  1102. element is specified, the move is relative to the current mouse
  1103. cursor. If an element is provided but no offset, the mouse will be
  1104. moved to the center of the element. If the element is not visible,
  1105. it will be scrolled into view.
  1106. Compatibility:
  1107. Due to limitations in the Webdriver 3 API, mouse movements have to be executed 'lazily' e.g. only right before a click() event occurs.
  1108. This is because there is no longer any persistent mouse location state; mouse movements are now totally atomic.
  1109. 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,
  1110. Aside from using javascript workarounds.
  1111. Output:
  1112. STRING -
  1113. Usage:
  1114. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  1115. # 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.
  1116. # 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.
  1117. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  1118. =cut
  1119. sub mouse_move_to_location {
  1120. my ( $self, %params ) = @_;
  1121. $params{element} = $params{element}{id} if exists $params{element};
  1122. if ( $self->{is_wd3}
  1123. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  1124. {
  1125. my $origin = $params{element};
  1126. my $move_action = {
  1127. type => "pointerMove",
  1128. duration => 0,
  1129. x => $params{xoffset} // 0,
  1130. y => $params{yoffset} // 0,
  1131. };
  1132. $move_action->{origin} =
  1133. { 'element-6066-11e4-a52e-4f735466cecf' => $origin }
  1134. if $origin;
  1135. _queue_action(
  1136. actions => [
  1137. {
  1138. type => "pointer",
  1139. id => 'mouse',
  1140. "parameters" => { "pointerType" => "mouse" },
  1141. actions => [$move_action],
  1142. }
  1143. ]
  1144. );
  1145. return 1;
  1146. }
  1147. my $res = { 'command' => 'mouseMoveToLocation' };
  1148. return $self->_execute_command( $res, \%params );
  1149. }
  1150. =head2 move_to
  1151. Synonymous with mouse_move_to_location
  1152. =cut
  1153. sub move_to {
  1154. return shift->mouse_move_to_location(@_);
  1155. }
  1156. =head2 get_capabilities
  1157. Description:
  1158. Retrieve the capabilities of the specified session.
  1159. Output:
  1160. HASH of all the capabilities.
  1161. Usage:
  1162. my $capab = $driver->get_capabilities();
  1163. print Dumper($capab);
  1164. =cut
  1165. sub get_capabilities {
  1166. my $self = shift;
  1167. my $res = { 'command' => 'getCapabilities' };
  1168. return $self->_execute_command($res);
  1169. }
  1170. =head2 get_timeouts
  1171. Description:
  1172. Get the currently configured values (ms) for the page load, script and implicit timeouts.
  1173. Compatibility:
  1174. Only available on WebDriver3 enabled selenium servers.
  1175. Usage:
  1176. $driver->get_timeouts();
  1177. =cut
  1178. sub get_timeouts {
  1179. my $self = shift;
  1180. my $res = { 'command' => 'getTimeouts' };
  1181. return $self->_execute_command( $res, {} );
  1182. }
  1183. =head2 set_timeout
  1184. Description:
  1185. Configure the amount of time that a particular type of operation can execute
  1186. for before they are aborted and a |Timeout| error is returned to the client.
  1187. Input:
  1188. type - <STRING> - The type of operation to set the timeout for.
  1189. Valid values are:
  1190. "script" : for script timeouts,
  1191. "implicit" : for modifying the implicit wait timeout
  1192. "page load" : for setting a page load timeout.
  1193. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  1194. commands are permitted to run.
  1195. Usage:
  1196. $driver->set_timeout('script', 1000);
  1197. =cut
  1198. sub set_timeout {
  1199. my ( $self, $type, $ms ) = @_;
  1200. if ( not defined $type ) {
  1201. croak "Expecting type";
  1202. }
  1203. $ms = _coerce_timeout_ms($ms);
  1204. $type = 'pageLoad'
  1205. if $type eq 'page load'
  1206. && $self->browser_name ne
  1207. 'MicrosoftEdge'; #XXX SHIM they changed the WC3 standard mid stream
  1208. my $res = { 'command' => 'setTimeout' };
  1209. my $params = { $type => $ms };
  1210. #XXX edge still follows earlier versions of the WC3 standard
  1211. if ( $self->browser_name eq 'MicrosoftEdge' ) {
  1212. $params->{ms} = $ms;
  1213. $params->{type} = $type;
  1214. }
  1215. return $self->_execute_command( $res, $params );
  1216. }
  1217. =head2 set_async_script_timeout
  1218. Description:
  1219. Set the amount of time, in milliseconds, that asynchronous scripts executed
  1220. by execute_async_script() are permitted to run before they are
  1221. aborted and a |Timeout| error is returned to the client.
  1222. Input:
  1223. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  1224. commands are permitted to run.
  1225. Usage:
  1226. $driver->set_async_script_timeout(1000);
  1227. =cut
  1228. sub set_async_script_timeout {
  1229. my ( $self, $ms ) = @_;
  1230. return $self->set_timeout( 'script', $ms ) if $self->{is_wd3};
  1231. $ms = _coerce_timeout_ms($ms);
  1232. my $res = { 'command' => 'setAsyncScriptTimeout' };
  1233. my $params = { 'ms' => $ms };
  1234. return $self->_execute_command( $res, $params );
  1235. }
  1236. =head2 set_implicit_wait_timeout
  1237. Description:
  1238. Set the amount of time the driver should wait when searching for elements.
  1239. When searching for a single element, the driver will poll the page until
  1240. an element is found or the timeout expires, whichever occurs first.
  1241. When searching for multiple elements, the driver should poll the page until
  1242. at least one element is found or the timeout expires, at which point it
  1243. will return an empty list. If this method is never called, the driver will
  1244. default to an implicit wait of 0ms.
  1245. This is exactly equivalent to calling L</set_timeout> with a type
  1246. arg of C<"implicit">.
  1247. Input:
  1248. Time in milliseconds.
  1249. Output:
  1250. Server Response Hash with no data returned back from the server.
  1251. Usage:
  1252. $driver->set_implicit_wait_timeout(10);
  1253. =cut
  1254. sub set_implicit_wait_timeout {
  1255. my ( $self, $ms ) = @_;
  1256. return $self->set_timeout( 'implicit', $ms ) if $self->{is_wd3};
  1257. $ms = _coerce_timeout_ms($ms);
  1258. my $res = { 'command' => 'setImplicitWaitTimeout' };
  1259. my $params = { 'ms' => $ms };
  1260. return $self->_execute_command( $res, $params );
  1261. }
  1262. =head2 pause
  1263. Description:
  1264. Pause execution for a specified interval of milliseconds.
  1265. Usage:
  1266. $driver->pause(10000); # 10 second delay
  1267. $driver->pause(); # 1 second delay default
  1268. DEPRECATED: consider using Time::HiRes instead.
  1269. =cut
  1270. sub pause {
  1271. my $self = shift;
  1272. my $timeout = ( shift // 1000 ) * 1000;
  1273. usleep($timeout);
  1274. }
  1275. =head2 close
  1276. Description:
  1277. Close the current window.
  1278. Usage:
  1279. $driver->close();
  1280. or
  1281. #close a popup window
  1282. my $handles = $driver->get_window_handles;
  1283. $driver->switch_to_window($handles->[1]);
  1284. $driver->close();
  1285. $driver->switch_to_window($handles->[0]);
  1286. =cut
  1287. sub close {
  1288. my $self = shift;
  1289. my $res = { 'command' => 'close' };
  1290. $self->_execute_command($res);
  1291. }
  1292. =head2 quit
  1293. Description:
  1294. DELETE the session, closing open browsers. We will try to call
  1295. this on our down when we get destroyed, but in the event that we
  1296. are demolished during global destruction, we will not be able to
  1297. close the browser. For your own unattended and/or complicated
  1298. tests, we recommend explicitly calling quit to make sure you're
  1299. not leaving orphan browsers around.
  1300. Note that as a Moo class, we use a subroutine called DEMOLISH that
  1301. takes the place of DESTROY; for more information, see
  1302. https://metacpan.org/pod/Moo#DEMOLISH.
  1303. Usage:
  1304. $driver->quit();
  1305. =cut
  1306. sub quit {
  1307. my $self = shift;
  1308. my $res = { 'command' => 'quit' };
  1309. $self->_execute_command($res);
  1310. $self->session_id(undef);
  1311. }
  1312. =head2 get_current_window_handle
  1313. Description:
  1314. Retrieve the current window handle.
  1315. Output:
  1316. STRING - the window handle
  1317. Usage:
  1318. print $driver->get_current_window_handle();
  1319. =cut
  1320. sub get_current_window_handle {
  1321. my $self = shift;
  1322. my $res = { 'command' => 'getCurrentWindowHandle' };
  1323. return $self->_execute_command($res);
  1324. }
  1325. =head2 get_window_handles
  1326. Description:
  1327. Retrieve the list of window handles used in the session.
  1328. Output:
  1329. ARRAY of STRING - list of the window handles
  1330. Usage:
  1331. print Dumper $driver->get_window_handles;
  1332. or
  1333. # get popup, close, then back
  1334. my $handles = $driver->get_window_handles;
  1335. $driver->switch_to_window($handles->[1]);
  1336. $driver->close;
  1337. $driver->switch_to_window($handles->[0]);
  1338. =cut
  1339. sub get_window_handles {
  1340. my $self = shift;
  1341. my $res = { 'command' => 'getWindowHandles' };
  1342. return $self->_execute_command($res);
  1343. }
  1344. =head2 get_window_size
  1345. Description:
  1346. Retrieve the window size
  1347. Compatibility:
  1348. The ability to get the size of arbitrary handles by passing input only exists in WebDriver2.
  1349. You will have to switch to the window first going forward.
  1350. Input:
  1351. STRING - <optional> - window handle (default is 'current' window)
  1352. Output:
  1353. HASH - containing keys 'height' & 'width'
  1354. Usage:
  1355. my $window_size = $driver->get_window_size();
  1356. print $window_size->{'height'}, $window_size->('width');
  1357. =cut
  1358. sub get_window_size {
  1359. my ( $self, $window ) = @_;
  1360. $window = ( defined $window ) ? $window : 'current';
  1361. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  1362. $res = { 'command' => 'getWindowRect', handle => $window }
  1363. if $self->{is_wd3};
  1364. return $self->_execute_command($res);
  1365. }
  1366. =head2 get_window_position
  1367. Description:
  1368. Retrieve the window position
  1369. Compatibility:
  1370. The ability to get the size of arbitrary handles by passing input only exists in WebDriver2.
  1371. You will have to switch to the window first going forward.
  1372. Input:
  1373. STRING - <optional> - window handle (default is 'current' window)
  1374. Output:
  1375. HASH - containing keys 'x' & 'y'
  1376. Usage:
  1377. my $window_size = $driver->get_window_position();
  1378. print $window_size->{'x'}, $window_size->('y');
  1379. =cut
  1380. sub get_window_position {
  1381. my ( $self, $window ) = @_;
  1382. $window = ( defined $window ) ? $window : 'current';
  1383. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  1384. $res = { 'command' => 'getWindowRect', handle => $window }
  1385. if $self->{is_wd3};
  1386. return $self->_execute_command($res);
  1387. }
  1388. =head2 get_current_url
  1389. Description:
  1390. Retrieve the url of the current page
  1391. Output:
  1392. STRING - url
  1393. Usage:
  1394. print $driver->get_current_url();
  1395. =cut
  1396. sub get_current_url {
  1397. my $self = shift;
  1398. my $res = { 'command' => 'getCurrentUrl' };
  1399. return $self->_execute_command($res);
  1400. }
  1401. =head2 navigate
  1402. Description:
  1403. Navigate to a given url. This is same as get() method.
  1404. Input:
  1405. STRING - url
  1406. Usage:
  1407. $driver->navigate('http://www.google.com');
  1408. =cut
  1409. sub navigate {
  1410. my ( $self, $url ) = @_;
  1411. $self->get($url);
  1412. }
  1413. =head2 get
  1414. Description:
  1415. Navigate to a given url
  1416. Input:
  1417. STRING - url
  1418. Usage:
  1419. $driver->get('http://www.google.com');
  1420. =cut
  1421. sub get {
  1422. my ( $self, $url ) = @_;
  1423. if ( $self->has_base_url && $url !~ m|://| ) {
  1424. $url =~ s|^/||;
  1425. $url = $self->base_url . "/" . $url;
  1426. }
  1427. my $res = { 'command' => 'get' };
  1428. my $params = { 'url' => $url };
  1429. return $self->_execute_command( $res, $params );
  1430. }
  1431. =head2 get_title
  1432. Description:
  1433. Get the current page title
  1434. Output:
  1435. STRING - Page title
  1436. Usage:
  1437. print $driver->get_title();
  1438. =cut
  1439. sub get_title {
  1440. my $self = shift;
  1441. my $res = { 'command' => 'getTitle' };
  1442. return $self->_execute_command($res);
  1443. }
  1444. =head2 go_back
  1445. Description:
  1446. Equivalent to hitting the back button on the browser.
  1447. Usage:
  1448. $driver->go_back();
  1449. =cut
  1450. sub go_back {
  1451. my $self = shift;
  1452. my $res = { 'command' => 'goBack' };
  1453. return $self->_execute_command($res);
  1454. }
  1455. =head2 go_forward
  1456. Description:
  1457. Equivalent to hitting the forward button on the browser.
  1458. Usage:
  1459. $driver->go_forward();
  1460. =cut
  1461. sub go_forward {
  1462. my $self = shift;
  1463. my $res = { 'command' => 'goForward' };
  1464. return $self->_execute_command($res);
  1465. }
  1466. =head2 refresh
  1467. Description:
  1468. Reload the current page.
  1469. Usage:
  1470. $driver->refresh();
  1471. =cut
  1472. sub refresh {
  1473. my $self = shift;
  1474. my $res = { 'command' => 'refresh' };
  1475. return $self->_execute_command($res);
  1476. }
  1477. =head2 has_javascript
  1478. Description:
  1479. returns true if javascript is enabled in the driver.
  1480. Compatibility:
  1481. Can't be false on WebDriver 3.
  1482. Usage:
  1483. if ($driver->has_javascript) { ...; }
  1484. =cut
  1485. sub has_javascript {
  1486. my $self = shift;
  1487. return int( $self->javascript );
  1488. }
  1489. =head2 execute_async_script
  1490. Description:
  1491. Inject a snippet of JavaScript into the page for execution in the context
  1492. of the currently selected frame. The executed script is assumed to be
  1493. asynchronous and must signal that is done by invoking the provided
  1494. callback, which is always provided as the final argument to the function.
  1495. The value to this callback will be returned to the client.
  1496. Asynchronous script commands may not span page loads. If an unload event
  1497. is fired while waiting for a script result, an error should be returned
  1498. to the client.
  1499. Input: 2 (1 optional)
  1500. Required:
  1501. STRING - Javascript to execute on the page
  1502. Optional:
  1503. ARRAY - list of arguments that need to be passed to the script.
  1504. Output:
  1505. {*} - Varied, depending on the type of result expected back from the script.
  1506. Usage:
  1507. my $script = q{
  1508. var arg1 = arguments[0];
  1509. var callback = arguments[arguments.length-1];
  1510. var elem = window.document.findElementById(arg1);
  1511. callback(elem);
  1512. };
  1513. my $elem = $driver->execute_async_script($script,'myid');
  1514. $elem->click;
  1515. =cut
  1516. sub execute_async_script {
  1517. my ( $self, $script, @args ) = @_;
  1518. if ( $self->has_javascript ) {
  1519. if ( not defined $script ) {
  1520. croak 'No script provided';
  1521. }
  1522. my $res =
  1523. { 'command' => 'executeAsyncScript' . $self->_execute_script_suffix };
  1524. # Check the args array if the elem obj is provided & replace it with
  1525. # JSON representation
  1526. for ( my $i = 0 ; $i < @args ; $i++ ) {
  1527. if ( Scalar::Util::blessed( $args[$i] )
  1528. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1529. {
  1530. if ( $self->{is_wd3} ) {
  1531. $args[$i] =
  1532. { 'element-6066-11e4-a52e-4f735466cecf' =>
  1533. ( $args[$i] )->{id} };
  1534. }
  1535. else {
  1536. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1537. }
  1538. }
  1539. }
  1540. my $params = { 'script' => $script, 'args' => \@args };
  1541. my $ret = $self->_execute_command( $res, $params );
  1542. # replace any ELEMENTS with WebElement
  1543. if ( ref($ret)
  1544. and ( ref($ret) eq 'HASH' )
  1545. and $self->_looks_like_element($ret) )
  1546. {
  1547. $ret = $self->webelement_class->new(
  1548. id => $ret,
  1549. driver => $self
  1550. );
  1551. }
  1552. return $ret;
  1553. }
  1554. else {
  1555. croak 'Javascript is not enabled on remote driver instance.';
  1556. }
  1557. }
  1558. =head2 execute_script
  1559. Description:
  1560. Inject a snippet of JavaScript into the page and return its result.
  1561. WebElements that should be passed to the script as an argument should be
  1562. specified in the arguments array as WebElement object. Likewise,
  1563. any WebElements in the script result will be returned as WebElement object.
  1564. Input: 2 (1 optional)
  1565. Required:
  1566. STRING - Javascript to execute on the page
  1567. Optional:
  1568. ARRAY - list of arguments that need to be passed to the script.
  1569. Output:
  1570. {*} - Varied, depending on the type of result expected back from the script.
  1571. Usage:
  1572. my $script = q{
  1573. var arg1 = arguments[0];
  1574. var elem = window.document.findElementById(arg1);
  1575. return elem;
  1576. };
  1577. my $elem = $driver->execute_script($script,'myid');
  1578. $elem->click;
  1579. =cut
  1580. sub execute_script {
  1581. my ( $self, $script, @args ) = @_;
  1582. if ( $self->has_javascript ) {
  1583. if ( not defined $script ) {
  1584. croak 'No script provided';
  1585. }
  1586. my $res =
  1587. { 'command' => 'executeScript' . $self->_execute_script_suffix };
  1588. # Check the args array if the elem obj is provided & replace it with
  1589. # JSON representation
  1590. for ( my $i = 0 ; $i < @args ; $i++ ) {
  1591. if ( Scalar::Util::blessed( $args[$i] )
  1592. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1593. {
  1594. if ( $self->{is_wd3} ) {
  1595. $args[$i] =
  1596. { 'element-6066-11e4-a52e-4f735466cecf' =>
  1597. ( $args[$i] )->{id} };
  1598. }
  1599. else {
  1600. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1601. }
  1602. }
  1603. }
  1604. my $params = { 'script' => $script, 'args' => [@args] };
  1605. my $ret = $self->_execute_command( $res, $params );
  1606. return $self->_convert_to_webelement($ret);
  1607. }
  1608. else {
  1609. croak 'Javascript is not enabled on remote driver instance.';
  1610. }
  1611. }
  1612. # _looks_like_element
  1613. # An internal method to check if a return value might be an element
  1614. sub _looks_like_element {
  1615. my ( $self, $maybe_element ) = @_;
  1616. return (
  1617. exists $maybe_element->{ELEMENT}
  1618. or exists $maybe_element->{'element-6066-11e4-a52e-4f735466cecf'}
  1619. );
  1620. }
  1621. # _convert_to_webelement
  1622. # An internal method used to traverse a data structure
  1623. # and convert any ELEMENTS with WebElements
  1624. sub _convert_to_webelement {
  1625. my ( $self, $ret ) = @_;
  1626. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  1627. if ( $self->_looks_like_element($ret) ) {
  1628. # replace an ELEMENT with WebElement
  1629. return $self->webelement_class->new(
  1630. id => $ret,
  1631. driver => $self
  1632. );
  1633. }
  1634. my %hash;
  1635. foreach my $key ( keys %$ret ) {
  1636. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1637. }
  1638. return \%hash;
  1639. }
  1640. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1641. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1642. return \@array;
  1643. }
  1644. return $ret;
  1645. }
  1646. =head2 screenshot
  1647. Description:
  1648. Get a screenshot of the current page as a base64 encoded image.
  1649. Optionally pass {'full' => 1} as argument to take a full screenshot and not
  1650. only the viewport. (Works only with firefox and geckodriver >= 0.24.0)
  1651. Output:
  1652. STRING - base64 encoded image
  1653. Usage:
  1654. print $driver->screenshot();
  1655. print $driver->screenshot({'full' => 1});
  1656. To conveniently write the screenshot to a file, see L</capture_screenshot>.
  1657. =cut
  1658. sub screenshot {
  1659. my ($self, $params) = @_;
  1660. $params //= { full => 0 };
  1661. croak "Full page screenshot only supported on geckodriver" if $params->{full} && ( $self->{browser_name} ne 'firefox' );
  1662. my $res = { 'command' => $params->{'full'} == 1 ? 'mozScreenshotFull' : 'screenshot' };
  1663. return $self->_execute_command($res);
  1664. }
  1665. =head2 capture_screenshot
  1666. Description:
  1667. Capture a screenshot and save as a PNG to provided file name.
  1668. (The method is compatible with the WWW::Selenium method of the same name)
  1669. Optionally pass {'full' => 1} as second argument to take a full screenshot
  1670. and not only the viewport. (Works only with firefox and geckodriver >= 0.24.0)
  1671. Output:
  1672. TRUE - (Screenshot is written to file)
  1673. Usage:
  1674. $driver->capture_screenshot($filename);
  1675. $driver->capture_screenshot($filename, {'full' => 1});
  1676. =cut
  1677. sub capture_screenshot {
  1678. my ( $self, $filename, $params ) = @_;
  1679. croak '$filename is required' unless $filename;
  1680. open( my $fh, '>', $filename );
  1681. binmode $fh;
  1682. print $fh MIME::Base64::decode_base64( $self->screenshot($params) );
  1683. CORE::close $fh;
  1684. return 1;
  1685. }
  1686. =head2 available_engines
  1687. Description:
  1688. List all available engines on the machine. To use an engine, it has to be present in this list.
  1689. Compatibility:
  1690. Does not appear to be available on Webdriver3 enabled selenium servers.
  1691. Output:
  1692. {Array.<string>} A list of available engines
  1693. Usage:
  1694. print Dumper $driver->available_engines;
  1695. =cut
  1696. #TODO emulate behavior on wd3?
  1697. #grep { eval { Selenium::Remote::Driver->new( browser => $_ ) } } (qw{firefox MicrosoftEdge chrome opera safari htmlunit iphone phantomjs},'internet_explorer');
  1698. #might do the trick
  1699. sub available_engines {
  1700. my ($self) = @_;
  1701. my $res = { 'command' => 'availableEngines' };
  1702. return $self->_execute_command($res);
  1703. }
  1704. =head2 switch_to_frame
  1705. Description:
  1706. Change focus to another frame on the page. If the frame ID is null, the
  1707. server will switch to the page's default content. You can also switch to a
  1708. WebElement, for e.g. you can find an iframe using find_element & then
  1709. provide that as an input to this method. Also see e.g.
  1710. Input: 1
  1711. Required:
  1712. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1713. mentioned.
  1714. Usage:
  1715. $driver->switch_to_frame('frame_1');
  1716. or
  1717. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1718. =cut
  1719. sub switch_to_frame {
  1720. my ( $self, $id ) = @_;
  1721. my $json_null = JSON::null;
  1722. my $params;
  1723. $id = ( defined $id ) ? $id : $json_null;
  1724. my $res = { 'command' => 'switchToFrame' };
  1725. if ( ref $id eq $self->webelement_class ) {
  1726. if ( $self->{is_wd3} ) {
  1727. $params =
  1728. { 'id' =>
  1729. { 'element-6066-11e4-a52e-4f735466cecf' => $id->{'id'} } };
  1730. }
  1731. else {
  1732. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1733. }
  1734. }
  1735. else {
  1736. $params = { 'id' => $id };
  1737. }
  1738. return $self->_execute_command( $res, $params );
  1739. }
  1740. =head2 switch_to_parent_frame
  1741. Webdriver 3 equivalent of calling switch_to_frame with no arguments (e.g. NULL frame).
  1742. This is actually called in that case, supposing you are using WD3 capable servers now.
  1743. =cut
  1744. sub switch_to_parent_frame {
  1745. my ($self) = @_;
  1746. my $res = { 'command' => 'switchToParentFrame' };
  1747. return $self->_execute_command($res);
  1748. }
  1749. =head2 switch_to_window
  1750. Description:
  1751. Change focus to another window. The window to change focus to may
  1752. be specified by its server assigned window handle, or by the value
  1753. of the page's window.name attribute.
  1754. If you wish to use the window name as the target, you'll need to
  1755. have set C<window.name> on the page either in app code or via
  1756. L</execute_script>, or pass a name as the second argument to the
  1757. C<window.open()> function when opening the new window. Note that
  1758. the window name used here has nothing to do with the window title,
  1759. or the C<< <title> >> element on the page.
  1760. Otherwise, use L</get_window_handles> and select a
  1761. Webdriver-generated handle from the output of that function.
  1762. Input: 1
  1763. Required:
  1764. STRING - Window handle or the Window name
  1765. Usage:
  1766. $driver->switch_to_window('MY Homepage');
  1767. or
  1768. # close a popup window and switch back
  1769. my $handles = $driver->get_window_handles;
  1770. $driver->switch_to_window($handles->[1]);
  1771. $driver->close;
  1772. $driver->switch_to_window($handles->[0]);
  1773. =cut
  1774. sub switch_to_window {
  1775. my ( $self, $name ) = @_;
  1776. if ( not defined $name ) {
  1777. return 'Window name not provided';
  1778. }
  1779. my $res = { 'command' => 'switchToWindow' };
  1780. my $params = { 'name' => $name, 'handle' => $name };
  1781. return $self->_execute_command( $res, $params );
  1782. }
  1783. =head2 set_window_position
  1784. Description:
  1785. Set the position (on screen) where you want your browser to be displayed.
  1786. Compatibility:
  1787. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1788. As such, the window handle argument below will be ignored in this context.
  1789. Input:
  1790. INT - x co-ordinate
  1791. INT - y co-ordinate
  1792. STRING - <optional> - window handle (default is 'current' window)
  1793. Output:
  1794. BOOLEAN - Success or failure
  1795. Usage:
  1796. $driver->set_window_position(50, 50);
  1797. =cut
  1798. sub set_window_position {
  1799. my ( $self, $x, $y, $window ) = @_;
  1800. $window = ( defined $window ) ? $window : 'current';
  1801. if ( not defined $x and not defined $y ) {
  1802. croak "X & Y co-ordinates are required";
  1803. }
  1804. croak qq{Error: In set_window_size, argument x "$x" isn't numeric}
  1805. unless Scalar::Util::looks_like_number($x);
  1806. croak qq{Error: In set_window_size, argument y "$y" isn't numeric}
  1807. unless Scalar::Util::looks_like_number($y);
  1808. $x +=
  1809. 0; # convert to numeric if a string, otherwise they'll be sent as strings
  1810. $y += 0;
  1811. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1812. my $params = { 'x' => $x, 'y' => $y };
  1813. if ( $self->{is_wd3} ) {
  1814. $res = { 'command' => 'setWindowRect', handle => $window };
  1815. }
  1816. my $ret = $self->_execute_command( $res, $params );
  1817. return $ret ? 1 : 0;
  1818. }
  1819. =head2 set_window_size
  1820. Description:
  1821. Set the size of the browser window
  1822. Compatibility:
  1823. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1824. As such, the window handle argument below will be ignored in this context.
  1825. Input:
  1826. INT - height of the window
  1827. INT - width of the window
  1828. STRING - <optional> - window handle (default is 'current' window)
  1829. Output:
  1830. BOOLEAN - Success or failure
  1831. Usage:
  1832. $driver->set_window_size(640, 480);
  1833. =cut
  1834. sub set_window_size {
  1835. my ( $self, $height, $width, $window ) = @_;
  1836. $window = ( defined $window ) ? $window : 'current';
  1837. if ( not defined $height and not defined $width ) {
  1838. croak "height & width of browser are required";
  1839. }
  1840. croak qq{Error: In set_window_size, argument height "$height" isn't numeric}
  1841. unless Scalar::Util::looks_like_number($height);
  1842. croak qq{Error: In set_window_size, argument width "$width" isn't numeric}
  1843. unless Scalar::Util::looks_like_number($width);
  1844. $height +=
  1845. 0; # convert to numeric if a string, otherwise they'll be sent as strings
  1846. $width += 0;
  1847. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1848. my $params = { 'height' => $height, 'width' => $width };
  1849. if ( $self->{is_wd3} ) {
  1850. $res = { 'command' => 'setWindowRect', handle => $window };
  1851. }
  1852. my $ret = $self->_execute_command( $res, $params );
  1853. return $ret ? 1 : 0;
  1854. }
  1855. =head2 maximize_window
  1856. Description:
  1857. Maximizes the browser window
  1858. Compatibility:
  1859. In webDriver 3 enabled selenium servers, you may only operate on the focused window.
  1860. As such, the window handle argument below will be ignored in this context.
  1861. Also, on chromedriver maximize is actually just setting the window size to the screen's
  1862. available height and width.
  1863. Input:
  1864. STRING - <optional> - window handle (default is 'current' window)
  1865. Output:
  1866. BOOLEAN - Success or failure
  1867. Usage:
  1868. $driver->maximize_window();
  1869. =cut
  1870. sub maximize_window {
  1871. my ( $self, $window ) = @_;
  1872. $window = ( defined $window ) ? $window : 'current';
  1873. my $res = { 'command' => 'maximizeWindow', 'window_handle' => $window };
  1874. my $ret = $self->_execute_command($res);
  1875. return $ret ? 1 : 0;
  1876. }
  1877. =head2 minimize_window
  1878. Description:
  1879. Minimizes the currently focused browser window (webdriver3 only)
  1880. Output:
  1881. BOOLEAN - Success or failure
  1882. Usage:
  1883. $driver->minimize_window();
  1884. =cut
  1885. sub minimize_window {
  1886. my ( $self, $window ) = @_;
  1887. $window = ( defined $window ) ? $window : 'current';
  1888. my $res = { 'command' => 'minimizeWindow', 'window_handle' => $window };
  1889. my $ret = $self->_execute_command($res);
  1890. return $ret ? 1 : 0;
  1891. }
  1892. =head2 fullscreen_window
  1893. Description:
  1894. Fullscreens the currently focused browser window (webdriver3 only)
  1895. Output:
  1896. BOOLEAN - Success or failure
  1897. Usage:
  1898. $driver->fullscreen_window();
  1899. =cut
  1900. sub fullscreen_window {
  1901. my ( $self, $window ) = @_;
  1902. $window = ( defined $window ) ? $window : 'current';
  1903. my $res = { 'command' => 'fullscreenWindow', 'window_handle' => $window };
  1904. my $ret = $self->_execute_command($res);
  1905. return $ret ? 1 : 0;
  1906. }
  1907. =head2 get_all_cookies
  1908. Description:
  1909. Retrieve all cookies visible to the current page. Each cookie will be
  1910. returned as a HASH reference with the following keys & their value types:
  1911. 'name' - STRING
  1912. 'value' - STRING
  1913. 'path' - STRING
  1914. 'domain' - STRING
  1915. 'secure' - BOOLEAN
  1916. Output:
  1917. ARRAY of HASHES - list of all the cookie hashes
  1918. Usage:
  1919. print Dumper($driver->get_all_cookies());
  1920. =cut
  1921. sub get_all_cookies {
  1922. my ($self) = @_;
  1923. my $res = { 'command' => 'getAllCookies' };
  1924. return $self->_execute_command($res);
  1925. }
  1926. =head2 add_cookie
  1927. Description:
  1928. Set a cookie on the domain.
  1929. Input: 2 (4 optional)
  1930. Required:
  1931. 'name' - STRING
  1932. 'value' - STRING
  1933. Optional:
  1934. 'path' - STRING
  1935. 'domain' - STRING
  1936. 'secure' - BOOLEAN - default false.
  1937. 'httponly' - BOOLEAN - default false.
  1938. 'expiry' - TIME_T - default 20 years in the future
  1939. Usage:
  1940. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0, 1)
  1941. =cut
  1942. sub add_cookie {
  1943. my ( $self, $name, $value, $path, $domain, $secure, $httponly, $expiry ) =
  1944. @_;
  1945. if ( ( not defined $name )
  1946. || ( not defined $value ) )
  1947. {
  1948. croak "Missing parameters";
  1949. }
  1950. my $res = { 'command' => 'addCookie' };
  1951. my $json_false = JSON::false;
  1952. my $json_true = JSON::true;
  1953. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1954. my $params = {
  1955. 'cookie' => {
  1956. 'name' => $name,
  1957. 'value' => $value,
  1958. 'path' => $path,
  1959. 'secure' => $secure,
  1960. }
  1961. };
  1962. $params->{cookie}->{domain} = $domain if $domain;
  1963. $params->{cookie}->{'httponly'} = $httponly if $httponly;
  1964. $params->{cookie}->{'expiry'} = $expiry if $expiry;
  1965. return $self->_execute_command( $res, $params );
  1966. }
  1967. =head2 delete_all_cookies
  1968. Description:
  1969. Delete all cookies visible to the current page.
  1970. Usage:
  1971. $driver->delete_all_cookies();
  1972. =cut
  1973. sub delete_all_cookies {
  1974. my ($self) = @_;
  1975. my $res = { 'command' => 'deleteAllCookies' };
  1976. return $self->_execute_command($res);
  1977. }
  1978. =head2 get_cookie_named
  1979. Basically get only the cookie with the provided name.
  1980. Probably preferable to pick it out of the list unless you expect a *really* long list.
  1981. Input:
  1982. Cookie Name - STRING
  1983. Returns cookie definition hash, much like the elements in get_all_cookies();
  1984. Compatibility:
  1985. Only available on webdriver3 enabled selenium servers.
  1986. =cut
  1987. sub get_cookie_named {
  1988. my ( $self, $cookie_name ) = @_;
  1989. my $res = { 'command' => 'getCookieNamed', 'name' => $cookie_name };
  1990. return $self->_execute_command($res);
  1991. }
  1992. =head2 delete_cookie_named
  1993. Description:
  1994. Delete the cookie with the given name. This command will be a no-op if there
  1995. is no such cookie visible to the current page.
  1996. Input: 1
  1997. Required:
  1998. STRING - name of cookie to delete
  1999. Usage:
  2000. $driver->delete_cookie_named('foo');
  2001. =cut
  2002. sub delete_cookie_named {
  2003. my ( $self, $cookie_name ) = @_;
  2004. if ( not defined $cookie_name ) {
  2005. croak "Cookie name not provided";
  2006. }
  2007. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  2008. return $self->_execute_command($res);
  2009. }
  2010. =head2 get_page_source
  2011. Description:
  2012. Get the current page source.
  2013. Output:
  2014. STRING - The page source.
  2015. Usage:
  2016. print $driver->get_page_source();
  2017. =cut
  2018. sub get_page_source {
  2019. my ($self) = @_;
  2020. my $res = { 'command' => 'getPageSource' };
  2021. return $self->_execute_command($res);
  2022. }
  2023. =head2 find_element
  2024. Description:
  2025. Search for an element on the page, starting from the document
  2026. root. The located element will be returned as a WebElement
  2027. object. If the element cannot be found, we will CROAK, killing
  2028. your script. If you wish for a warning instead, use the
  2029. parameterized version of the finders:
  2030. find_element_by_class
  2031. find_element_by_class_name
  2032. find_element_by_css
  2033. find_element_by_id
  2034. find_element_by_link
  2035. find_element_by_link_text
  2036. find_element_by_name
  2037. find_element_by_partial_link_text
  2038. find_element_by_tag_name
  2039. find_element_by_xpath
  2040. These functions all take a single STRING argument: the locator
  2041. search target of the element you want. If the element is found, we
  2042. will receive a WebElement. Otherwise, we will return 0. Note that
  2043. invoking methods on 0 will of course kill your script.
  2044. Input: 2 (1 optional)
  2045. Required:
  2046. STRING - The search target.
  2047. Optional:
  2048. STRING - Locator scheme to use to search the element, available schemes:
  2049. {class, class_name, css, id, link, link_text, partial_link_text,
  2050. tag_name, name, xpath}
  2051. Defaults to 'xpath' if not configured global during instantiation.
  2052. Output:
  2053. Selenium::Remote::WebElement - WebElement Object
  2054. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  2055. Usage:
  2056. $driver->find_element("//input[\@name='q']");
  2057. =cut
  2058. sub find_element {
  2059. my ( $self, $query, $method ) = @_;
  2060. if ( not defined $query ) {
  2061. croak 'Search string to find element not provided.';
  2062. }
  2063. my $res = { 'command' => 'findElement' };
  2064. my $params = $self->_build_find_params( $method, $query );
  2065. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  2066. if ($@) {
  2067. if ( $@ =~
  2068. /(An element could not be located on the page using the given search parameters)/
  2069. )
  2070. {
  2071. # give details on what element wasn't found
  2072. $@ = "$1: $query,$params->{using}";
  2073. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  2074. croak $@;
  2075. }
  2076. else {
  2077. # re throw if the exception wasn't what we expected
  2078. die $@;
  2079. }
  2080. }
  2081. return $self->webelement_class->new(
  2082. id => $ret_data,
  2083. driver => $self
  2084. );
  2085. }
  2086. =head2 find_elements
  2087. Description:
  2088. Search for multiple elements on the page, starting from the document root.
  2089. The located elements will be returned as an array of WebElement object.
  2090. Input: 2 (1 optional)
  2091. Required:
  2092. STRING - The search target.
  2093. Optional:
  2094. STRING - Locator scheme to use to search the element, available schemes:
  2095. {class, class_name, css, id, link, link_text, partial_link_text,
  2096. tag_name, name, xpath}
  2097. Defaults to 'xpath' if not configured global during instantiation.
  2098. Output:
  2099. ARRAY or ARRAYREF of WebElement Objects
  2100. Usage:
  2101. $driver->find_elements("//input");
  2102. =cut
  2103. sub find_elements {
  2104. my ( $self, $query, $method ) = @_;
  2105. if ( not defined $query ) {
  2106. croak 'Search string to find element not provided.';
  2107. }
  2108. my $res = { 'command' => 'findElements' };
  2109. my $params = $self->_build_find_params( $method, $query );
  2110. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  2111. if ($@) {
  2112. if ( $@ =~
  2113. /(An element could not be located on the page using the given search parameters)/
  2114. )
  2115. {
  2116. # give details on what element wasn't found
  2117. $@ = "$1: $query,$params->{using}";
  2118. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  2119. croak $@;
  2120. }
  2121. else {
  2122. # re throw if the exception wasn't what we expected
  2123. die $@;
  2124. }
  2125. }
  2126. my $elem_obj_arr = [];
  2127. foreach (@$ret_data) {
  2128. push(
  2129. @$elem_obj_arr,
  2130. $self->webelement_class->new(
  2131. id => $_,
  2132. driver => $self
  2133. )
  2134. );
  2135. }
  2136. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  2137. }
  2138. =head2 find_child_element
  2139. Description:
  2140. Search for an element on the page, starting from the identified element. The
  2141. located element will be returned as a WebElement object.
  2142. Input: 3 (1 optional)
  2143. Required:
  2144. Selenium::Remote::WebElement - WebElement object from where you want to
  2145. start searching.
  2146. STRING - The search target. (Do not use a double whack('//')
  2147. in an xpath to search for a child element
  2148. ex: '//option[@id="something"]'
  2149. instead use a dot whack ('./')
  2150. ex: './option[@id="something"]')
  2151. Optional:
  2152. STRING - Locator scheme to use to search the element, available schemes:
  2153. {class, class_name, css, id, link, link_text, partial_link_text,
  2154. tag_name, name, xpath}
  2155. Defaults to 'xpath' if not configured global during instantiation.
  2156. Output:
  2157. WebElement Object
  2158. Usage:
  2159. my $elem1 = $driver->find_element("//select[\@name='ned']");
  2160. # note the usage of ./ when searching for a child element instead of //
  2161. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  2162. =cut
  2163. sub find_child_element {
  2164. my ( $self, $elem, $query, $method ) = @_;
  2165. if ( ( not defined $elem ) || ( not defined $query ) ) {
  2166. croak "Missing parameters";
  2167. }
  2168. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  2169. my $params = $self->_build_find_params( $method, $query );
  2170. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  2171. if ($@) {
  2172. if ( $@ =~
  2173. /(An element could not be located on the page using the given search parameters)/
  2174. )
  2175. {
  2176. # give details on what element wasn't found
  2177. $@ = "$1: $query,$params->{using}";
  2178. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  2179. croak $@;
  2180. }
  2181. else {
  2182. # re throw if the exception wasn't what we expected
  2183. die $@;
  2184. }
  2185. }
  2186. return $self->webelement_class->new(
  2187. id => $ret_data,
  2188. driver => $self
  2189. );
  2190. }
  2191. =head2 find_child_elements
  2192. Description:
  2193. Search for multiple element on the page, starting from the identified
  2194. element. The located elements will be returned as an array of WebElement
  2195. objects.
  2196. Input: 3 (1 optional)
  2197. Required:
  2198. Selenium::Remote::WebElement - WebElement object from where you want to
  2199. start searching.
  2200. STRING - The search target.
  2201. Optional:
  2202. STRING - Locator scheme to use to search the element, available schemes:
  2203. {class, class_name, css, id, link, link_text, partial_link_text,
  2204. tag_name, name, xpath}
  2205. Defaults to 'xpath' if not configured global during instantiation.
  2206. Output:
  2207. ARRAY of WebElement Objects.
  2208. Usage:
  2209. my $elem1 = $driver->find_element("//select[\@name='ned']");
  2210. # note the usage of ./ when searching for a child element instead of //
  2211. my $child = $driver->find_child_elements($elem1, "./option");
  2212. =cut
  2213. sub find_child_elements {
  2214. my ( $self, $elem, $query, $method ) = @_;
  2215. if ( ( not defined $elem ) || ( not defined $query ) ) {
  2216. croak "Missing parameters";
  2217. }
  2218. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  2219. my $params = $self->_build_find_params( $method, $query );
  2220. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  2221. if ($@) {
  2222. if ( $@ =~
  2223. /(An element could not be located on the page using the given search parameters)/
  2224. )
  2225. {
  2226. # give details on what element wasn't found
  2227. $@ = "$1: $query,$params->{using}";
  2228. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  2229. croak $@;
  2230. }
  2231. else {
  2232. # re throw if the exception wasn't what we expected
  2233. die $@;
  2234. }
  2235. }
  2236. my $elem_obj_arr = [];
  2237. my $i = 0;
  2238. foreach (@$ret_data) {
  2239. $elem_obj_arr->[$i] = $self->webelement_class->new(
  2240. id => $_,
  2241. driver => $self
  2242. );
  2243. $i++;
  2244. }
  2245. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  2246. }
  2247. =head2 find_element_by_class
  2248. See L</find_element>.
  2249. =head2 find_element_by_class_name
  2250. See L</find_element>.
  2251. =head2 find_element_by_css
  2252. See L</find_element>.
  2253. =head2 find_element_by_id
  2254. See L</find_element>.
  2255. =head2 find_element_by_link
  2256. See L</find_element>.
  2257. =head2 find_element_by_link_text
  2258. See L</find_element>.
  2259. =head2 find_element_by_name
  2260. See L</find_element>.
  2261. =head2 find_element_by_partial_link_text
  2262. See L</find_element>.
  2263. =head2 find_element_by_tag_name
  2264. See L</find_element>.
  2265. =head2 find_element_by_xpath
  2266. See L</find_element>.
  2267. =head2 get_active_element
  2268. Description:
  2269. Get the element on the page that currently has focus.. The located element
  2270. will be returned as a WebElement object.
  2271. Output:
  2272. WebElement Object
  2273. Usage:
  2274. $driver->get_active_element();
  2275. =cut
  2276. sub _build_find_params {
  2277. my ( $self, $method, $query ) = @_;
  2278. my $using = $self->_build_using($method);
  2279. # geckodriver doesn't accept name as a valid selector
  2280. if ( $self->isa('Selenium::Firefox') && $using eq 'name' ) {
  2281. return {
  2282. using => 'css selector',
  2283. value => qq{[name="$query"]}
  2284. };
  2285. }
  2286. else {
  2287. return {
  2288. using => $using,
  2289. value => $query
  2290. };
  2291. }
  2292. }
  2293. sub _build_using {
  2294. my ( $self, $method ) = @_;
  2295. if ($method) {
  2296. if ( $self->FINDERS->{$method} ) {
  2297. return $self->FINDERS->{$method};
  2298. }
  2299. else {
  2300. croak 'Bad method, expected: '
  2301. . join( ', ', keys %{ $self->FINDERS } )
  2302. . ", got $method";
  2303. }
  2304. }
  2305. else {
  2306. return $self->default_finder;
  2307. }
  2308. }
  2309. sub get_active_element {
  2310. my ($self) = @_;
  2311. my $res = { 'command' => 'getActiveElement' };
  2312. my $ret_data = eval { $self->_execute_command($res) };
  2313. if ($@) {
  2314. croak $@;
  2315. }
  2316. else {
  2317. return $self->webelement_class->new(
  2318. id => $ret_data,
  2319. driver => $self
  2320. );
  2321. }
  2322. }
  2323. =head2 cache_status
  2324. Description:
  2325. Get the status of the html5 application cache.
  2326. Usage:
  2327. print $driver->cache_status;
  2328. Output:
  2329. <number> - Status code for application cache: {UNCACHED = 0, IDLE = 1, CHECKING = 2, DOWNLOADING = 3, UPDATE_READY = 4, OBSOLETE = 5}
  2330. =cut
  2331. sub cache_status {
  2332. my ($self) = @_;
  2333. my $res = { 'command' => 'cacheStatus' };
  2334. return $self->_execute_command($res);
  2335. }
  2336. =head2 set_geolocation
  2337. Description:
  2338. Set the current geographic location - note that your driver must
  2339. implement this endpoint, or else it will crash your session. At the
  2340. very least, it works in v2.12 of Chromedriver.
  2341. Input:
  2342. Required:
  2343. HASH: A hash with key C<location> whose value is a Location hashref. See
  2344. usage section for example.
  2345. Usage:
  2346. $driver->set_geolocation( location => {
  2347. latitude => 40.714353,
  2348. longitude => -74.005973,
  2349. altitude => 0.056747
  2350. });
  2351. Output:
  2352. BOOLEAN - success or failure
  2353. =cut
  2354. sub set_geolocation {
  2355. my ( $self, %params ) = @_;
  2356. my $res = { 'command' => 'setGeolocation' };
  2357. return $self->_execute_command( $res, \%params );
  2358. }
  2359. =head2 get_geolocation
  2360. Description:
  2361. Get the current geographic location. Note that your webdriver must
  2362. implement this endpoint - otherwise, it will crash your session. At
  2363. the time of release, we couldn't get this to work on the desktop
  2364. FirefoxDriver or desktop Chromedriver.
  2365. Usage:
  2366. print $driver->get_geolocation;
  2367. Output:
  2368. { latitude: number, longitude: number, altitude: number } - The current geo location.
  2369. =cut
  2370. sub get_geolocation {
  2371. my ($self) = @_;
  2372. my $res = { 'command' => 'getGeolocation' };
  2373. return $self->_execute_command($res);
  2374. }
  2375. =head2 get_log
  2376. Description:
  2377. Get the log for a given log type. Log buffer is reset after each request.
  2378. Input:
  2379. Required:
  2380. <STRING> - Type of log to retrieve:
  2381. {client|driver|browser|server}. There may be others available; see
  2382. get_log_types for a full list for your driver.
  2383. Usage:
  2384. $driver->get_log( $log_type );
  2385. Output:
  2386. <ARRAY|ARRAYREF> - An array of log entries since the most recent request.
  2387. =cut
  2388. sub get_log {
  2389. my ( $self, $type ) = @_;
  2390. my $res = { 'command' => 'getLog' };
  2391. return $self->_execute_command( $res, { type => $type } );
  2392. }
  2393. =head2 get_log_types
  2394. Description:
  2395. Get available log types. By default, every driver should have client,
  2396. driver, browser, and server types, but there may be more available,
  2397. depending on your driver.
  2398. Usage:
  2399. my @types = $driver->get_log_types;
  2400. $driver->get_log($types[0]);
  2401. Output:
  2402. <ARRAYREF> - The list of log types.
  2403. =cut
  2404. sub get_log_types {
  2405. my ($self) = @_;
  2406. my $res = { 'command' => 'getLogTypes' };
  2407. return $self->_execute_command($res);
  2408. }
  2409. =head2 set_orientation
  2410. Description:
  2411. Set the browser orientation.
  2412. Input:
  2413. Required:
  2414. <STRING> - Orientation {LANDSCAPE|PORTRAIT}
  2415. Usage:
  2416. $driver->set_orientation( $orientation );
  2417. Output:
  2418. BOOLEAN - success or failure
  2419. =cut
  2420. sub set_orientation {
  2421. my ( $self, $orientation ) = @_;
  2422. my $res = { 'command' => 'setOrientation' };
  2423. return $self->_execute_command( $res, { orientation => $orientation } );
  2424. }
  2425. =head2 get_orientation
  2426. Description:
  2427. Get the current browser orientation. Returns either LANDSCAPE|PORTRAIT.
  2428. Usage:
  2429. print $driver->get_orientation;
  2430. Output:
  2431. <STRING> - your orientation.
  2432. =cut
  2433. sub get_orientation {
  2434. my ($self) = @_;
  2435. my $res = { 'command' => 'getOrientation' };
  2436. return $self->_execute_command($res);
  2437. }
  2438. =head2 send_modifier
  2439. Description:
  2440. Send an event to the active element to depress or release a modifier key.
  2441. Input: 2
  2442. Required:
  2443. 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
  2444. isdown - Boolean/String - Whether to generate a key down or key up
  2445. Usage:
  2446. $driver->send_modifier('Alt','down');
  2447. $elem->send_keys('c');
  2448. $driver->send_modifier('Alt','up');
  2449. or
  2450. $driver->send_modifier('Alt',1);
  2451. $elem->send_keys('c');
  2452. $driver->send_modifier('Alt',0);
  2453. =cut
  2454. sub send_modifier {
  2455. my ( $self, $modifier, $isdown ) = @_;
  2456. if ( $isdown =~ /(down|up)/ ) {
  2457. $isdown = $isdown =~ /down/ ? 1 : 0;
  2458. }
  2459. if ( $self->{is_wd3}
  2460. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2461. {
  2462. my $acts = [
  2463. {
  2464. type => $isdown ? 'keyDown' : 'keyUp',
  2465. value => KEYS->{ lc($modifier) },
  2466. },
  2467. ];
  2468. my $action = {
  2469. actions => [
  2470. {
  2471. id => 'key',
  2472. type => 'key',
  2473. actions => $acts,
  2474. }
  2475. ]
  2476. };
  2477. _queue_action(%$action);
  2478. return 1;
  2479. }
  2480. my $res = { 'command' => 'sendModifier' };
  2481. my $params = {
  2482. value => $modifier,
  2483. isdown => $isdown
  2484. };
  2485. return $self->_execute_command( $res, $params );
  2486. }
  2487. =head2 compare_elements
  2488. Description:
  2489. Test if two element IDs refer to the same DOM element.
  2490. Input: 2
  2491. Required:
  2492. Selenium::Remote::WebElement - WebElement Object
  2493. Selenium::Remote::WebElement - WebElement Object
  2494. Output:
  2495. BOOLEAN
  2496. Usage:
  2497. $driver->compare_elements($elem_obj1, $elem_obj2);
  2498. =cut
  2499. sub compare_elements {
  2500. my ( $self, $elem1, $elem2 ) = @_;
  2501. my $res = {
  2502. 'command' => 'elementEquals',
  2503. 'id' => $elem1->{id},
  2504. 'other' => $elem2->{id}
  2505. };
  2506. return $self->_execute_command($res);
  2507. }
  2508. =head2 click
  2509. Description:
  2510. Click any mouse button (at the coordinates set by the last moveto command).
  2511. Input:
  2512. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  2513. defaults to 'LEFT'
  2514. queue - (optional) queue the click, rather than executing it. WD3 only.
  2515. Usage:
  2516. $driver->click('LEFT');
  2517. $driver->click(1); #MIDDLE
  2518. $driver->click('RIGHT');
  2519. $driver->click; #Defaults to left
  2520. =cut
  2521. sub click {
  2522. my ( $self, $button, $append ) = @_;
  2523. $button = _get_button($button);
  2524. my $res = { 'command' => 'click' };
  2525. my $params = { 'button' => $button };
  2526. if ( $self->{is_wd3}
  2527. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2528. {
  2529. $params = {
  2530. actions => [
  2531. {
  2532. type => "pointer",
  2533. id => 'mouse',
  2534. parameters => { "pointerType" => "mouse" },
  2535. actions => [
  2536. {
  2537. type => "pointerDown",
  2538. duration => 0,
  2539. button => $button,
  2540. },
  2541. {
  2542. type => "pointerUp",
  2543. duration => 0,
  2544. button => $button,
  2545. },
  2546. ],
  2547. }
  2548. ],
  2549. };
  2550. if ($append) {
  2551. _queue_action(%$params);
  2552. return 1;
  2553. }
  2554. return $self->general_action(%$params);
  2555. }
  2556. return $self->_execute_command( $res, $params );
  2557. }
  2558. sub _get_button {
  2559. my $button = shift;
  2560. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  2561. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  2562. return $button_enum->{ uc $1 };
  2563. }
  2564. if ( defined $button && $button =~ /(0|1|2)/ ) {
  2565. return $1;
  2566. }
  2567. return 0;
  2568. }
  2569. =head2 double_click
  2570. Description:
  2571. Double-clicks at the current mouse coordinates (set by moveto).
  2572. Compatibility:
  2573. On webdriver3 enabled servers, you can double click arbitrary mouse buttons.
  2574. Usage:
  2575. $driver->double_click(button);
  2576. =cut
  2577. sub double_click {
  2578. my ( $self, $button ) = @_;
  2579. $button = _get_button($button);
  2580. if ( $self->{is_wd3}
  2581. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2582. {
  2583. $self->click( $button, 1 );
  2584. $self->click( $button, 1 );
  2585. $self->general_action();
  2586. }
  2587. my $res = { 'command' => 'doubleClick' };
  2588. return $self->_execute_command($res);
  2589. }
  2590. =head2 button_down
  2591. Description:
  2592. Click and hold the left mouse button (at the coordinates set by the
  2593. last moveto command). Note that the next mouse-related command that
  2594. should follow is buttonup . Any other mouse command (such as click
  2595. or another call to buttondown) will yield undefined behaviour.
  2596. Compatibility:
  2597. On WebDriver 3 enabled servers, all this does is queue a button down action.
  2598. You will either have to call general_action() to perform the queue, or an action like click() which also clears the queue.
  2599. Usage:
  2600. $self->button_down;
  2601. =cut
  2602. sub button_down {
  2603. my ($self) = @_;
  2604. if ( $self->{is_wd3}
  2605. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2606. {
  2607. my $params = {
  2608. actions => [
  2609. {
  2610. type => "pointer",
  2611. id => 'mouse',
  2612. parameters => { "pointerType" => "mouse" },
  2613. actions => [
  2614. {
  2615. type => "pointerDown",
  2616. duration => 0,
  2617. button => 0,
  2618. },
  2619. ],
  2620. }
  2621. ],
  2622. };
  2623. _queue_action(%$params);
  2624. return 1;
  2625. }
  2626. my $res = { 'command' => 'buttonDown' };
  2627. return $self->_execute_command($res);
  2628. }
  2629. =head2 button_up
  2630. Description:
  2631. Releases the mouse button previously held (where the mouse is
  2632. currently at). Must be called once for every buttondown command
  2633. issued. See the note in click and buttondown about implications of
  2634. out-of-order commands.
  2635. Compatibility:
  2636. On WebDriver 3 enabled servers, all this does is queue a button down action.
  2637. You will either have to call general_action() to perform the queue, or an action like click() which also clears the queue.
  2638. Usage:
  2639. $self->button_up;
  2640. =cut
  2641. sub button_up {
  2642. my ($self) = @_;
  2643. if ( $self->{is_wd3}
  2644. && !( grep { $self->browser_name eq $_ } qw{MicrosoftEdge} ) )
  2645. {
  2646. my $params = {
  2647. actions => [
  2648. {
  2649. type => "pointer",
  2650. id => 'mouse',
  2651. parameters => { "pointerType" => "mouse" },
  2652. actions => [
  2653. {
  2654. type => "pointerDown",
  2655. duration => 0,
  2656. button => 0,
  2657. },
  2658. ],
  2659. }
  2660. ],
  2661. };
  2662. _queue_action(%$params);
  2663. return 1;
  2664. }
  2665. my $res = { 'command' => 'buttonUp' };
  2666. return $self->_execute_command($res);
  2667. }
  2668. =head2 upload_file
  2669. Description:
  2670. Upload a file from the local machine to the selenium server
  2671. machine. That file then can be used for testing file upload on web
  2672. forms. Returns the remote-server's path to the file.
  2673. Passing raw data as an argument past the filename will upload
  2674. that rather than the file's contents.
  2675. When passing raw data, be advised that it expects a zipped
  2676. and then base64 encoded version of a single file.
  2677. Multiple files and/or directories are not supported by the remote server.
  2678. Usage:
  2679. my $remote_fname = $driver->upload_file( $fname );
  2680. my $element = $driver->find_element( '//input[@id="file"]' );
  2681. $element->send_keys( $remote_fname );
  2682. =cut
  2683. # this method duplicates upload() method in the
  2684. # org.openqa.selenium.remote.RemoteWebElement java class.
  2685. sub upload_file {
  2686. my ( $self, $filename, $raw_content ) = @_;
  2687. my $params;
  2688. if ( defined $raw_content ) {
  2689. #If no processing is passed, send the argument raw
  2690. $params = { file => $raw_content };
  2691. }
  2692. else {
  2693. #Otherwise, zip/base64 it.
  2694. $params = $self->_prepare_file($filename);
  2695. }
  2696. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  2697. my $ret = $self->_execute_command( $res, $params );
  2698. return $ret;
  2699. }
  2700. sub _prepare_file {
  2701. my ( $self, $filename ) = @_;
  2702. if ( not -r $filename ) { croak "upload_file: no such file: $filename"; }
  2703. my $string = ""; # buffer
  2704. my $zip = Archive::Zip->new();
  2705. $zip->addFile( $filename, basename($filename) );
  2706. if ( $zip->writeToFileHandle( IO::String->new($string) ) != AZ_OK ) {
  2707. die 'zip failed';
  2708. }
  2709. return { file => MIME::Base64::encode_base64( $string, '' ) };
  2710. }
  2711. =head2 get_text
  2712. Description:
  2713. Get the text of a particular element. Wrapper around L<find_element()>
  2714. Usage:
  2715. $text = $driver->get_text("//div[\@name='q']");
  2716. =cut
  2717. sub get_text {
  2718. my $self = shift;
  2719. return $self->find_element(@_)->get_text();
  2720. }
  2721. =head2 get_body
  2722. Description:
  2723. Get the current text for the whole body. If you want the entire raw HTML instead,
  2724. See L<get_page_source>.
  2725. Usage:
  2726. $body_text = $driver->get_body();
  2727. =cut
  2728. sub get_body {
  2729. my $self = shift;
  2730. return $self->get_text( '//body', 'xpath' );
  2731. }
  2732. =head2 get_path
  2733. Description:
  2734. Get the path part of the current browser location.
  2735. Usage:
  2736. $path = $driver->get_path();
  2737. =cut
  2738. sub get_path {
  2739. my $self = shift;
  2740. my $location = $self->get_current_url;
  2741. $location =~ s/\?.*//; # strip of query params
  2742. $location =~ s/#.*//; # strip of anchors
  2743. $location =~ s#^https?://[^/]+##; # strip off host
  2744. return $location;
  2745. }
  2746. =head2 get_user_agent
  2747. Description:
  2748. Convenience method to get the user agent string, according to the
  2749. browser's value for window.navigator.userAgent.
  2750. Usage:
  2751. $user_agent = $driver->get_user_agent()
  2752. =cut
  2753. sub get_user_agent {
  2754. my $self = shift;
  2755. return $self->execute_script('return window.navigator.userAgent;');
  2756. }
  2757. =head2 set_inner_window_size
  2758. Description:
  2759. Set the inner window size by closing the current window and
  2760. reopening the current page in a new window. This can be useful
  2761. when using browsers to mock as mobile devices.
  2762. This sub will be fired automatically if you set the
  2763. C<inner_window_size> hash key option during instantiation.
  2764. Input:
  2765. INT - height of the window
  2766. INT - width of the window
  2767. Output:
  2768. BOOLEAN - Success or failure
  2769. Usage:
  2770. $driver->set_inner_window_size(640, 480)
  2771. =cut
  2772. sub set_inner_window_size {
  2773. my $self = shift;
  2774. my $height = shift;
  2775. my $width = shift;
  2776. my $location = $self->get_current_url;
  2777. $self->execute_script( 'window.open("' . $location . '", "_blank")' );
  2778. $self->close;
  2779. my @handles = @{ $self->get_window_handles };
  2780. $self->switch_to_window( pop @handles );
  2781. my @resize = (
  2782. 'window.innerHeight = ' . $height,
  2783. 'window.innerWidth = ' . $width,
  2784. 'return 1'
  2785. );
  2786. return $self->execute_script( join( ';', @resize ) ) ? 1 : 0;
  2787. }
  2788. =head2 get_local_storage_item
  2789. Description:
  2790. Get the value of a local storage item specified by the given key.
  2791. Input: 1
  2792. Required:
  2793. STRING - name of the key to be retrieved
  2794. Output:
  2795. STRING - value of the local storage item
  2796. Usage:
  2797. $driver->get_local_storage_item('key')
  2798. =cut
  2799. sub get_local_storage_item {
  2800. my ( $self, $key ) = @_;
  2801. my $res = { 'command' => 'getLocalStorageItem' };
  2802. my $params = { 'key' => $key };
  2803. return $self->_execute_command( $res, $params );
  2804. }
  2805. =head2 delete_local_storage_item
  2806. Description:
  2807. Get the value of a local storage item specified by the given key.
  2808. Input: 1
  2809. Required
  2810. STRING - name of the key to be deleted
  2811. Usage:
  2812. $driver->delete_local_storage_item('key')
  2813. =cut
  2814. sub delete_local_storage_item {
  2815. my ( $self, $key ) = @_;
  2816. my $res = { 'command' => 'deleteLocalStorageItem' };
  2817. my $params = { 'key' => $key };
  2818. return $self->_execute_command( $res, $params );
  2819. }
  2820. sub _coerce_timeout_ms {
  2821. my ($ms) = @_;
  2822. if ( defined $ms ) {
  2823. return _coerce_number($ms);
  2824. }
  2825. else {
  2826. croak 'Expecting a timeout in ms';
  2827. }
  2828. }
  2829. sub _coerce_number {
  2830. my ($maybe_number) = @_;
  2831. if ( Scalar::Util::looks_like_number($maybe_number) ) {
  2832. return $maybe_number + 0;
  2833. }
  2834. else {
  2835. croak "Expecting a number, not: $maybe_number";
  2836. }
  2837. }
  2838. 1;
  2839. __END__
  2840. =head1 SEE ALSO
  2841. L<https://github.com/SeleniumHQ/selenium> - the main selenium RC project
  2842. L<https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol> - the "legacy" webdriver specification
  2843. L<https://www.w3.org/TR/webdriver/> - the WC3 WebDriver 3 specification
  2844. L<https://github.com/teodesian/Selenium-Remote-Driver/wiki>
  2845. Brownie
  2846. Wight
  2847. =cut