1
0

Driver.pm 102 KB

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