Driver.pm 106 KB

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