Driver.pm 78 KB

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