1
0

Driver.pm 76 KB

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