Driver.pm 78 KB

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