Driver.pm 102 KB

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