Driver.pm 79 KB

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