1
0

Driver.pm 76 KB

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