1
0

Driver.pm 99 KB

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