Driver.pm 106 KB

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