Driver.pm 107 KB

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