1
0

Driver.pm 105 KB

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