Driver.pm 103 KB

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