Driver.pm 98 KB

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