Driver.pm 107 KB

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