Driver.pm 106 KB

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