Driver.pm 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808
  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. Input:
  823. Time in milliseconds.
  824. Output:
  825. Server Response Hash with no data returned back from the server.
  826. Usage:
  827. $driver->set_implicit_wait_timeout(10);
  828. =cut
  829. sub set_implicit_wait_timeout {
  830. my ( $self, $ms ) = @_;
  831. $ms = _coerce_timeout_ms( $ms );
  832. my $res = { 'command' => 'setImplicitWaitTimeout' };
  833. my $params = { 'ms' => $ms };
  834. return $self->_execute_command( $res, $params );
  835. }
  836. =head2 pause
  837. Description:
  838. Pause execution for a specified interval of milliseconds.
  839. Usage:
  840. $driver->pause(10000); # 10 second delay
  841. $driver->pause(); # 1 second delay default
  842. =cut
  843. sub pause {
  844. my $self = shift;
  845. my $timeout = ( shift // 1000 ) / 1000;
  846. select( undef, undef, undef, $timeout ); # Fractional-second sleep
  847. }
  848. =head2 close
  849. Description:
  850. Close the current window.
  851. Usage:
  852. $driver->close();
  853. or
  854. #close a popup window
  855. my $handles = $driver->get_window_handles;
  856. $driver->switch_to_window($handles->[1]);
  857. $driver->close();
  858. $driver->switch_to_window($handles->[0]);
  859. =cut
  860. sub close {
  861. my $self = shift;
  862. my $res = { 'command' => 'close' };
  863. $self->_execute_command($res);
  864. }
  865. =head2 quit
  866. Description:
  867. DELETE the session, closing open browsers. We will try to call
  868. this on our down when we get destroyed, but in the event that we
  869. are demolished during global destruction, we will not be able to
  870. close the browser. For your own unattended and/or complicated
  871. tests, we recommend explicitly calling quit to make sure you're
  872. not leaving orphan browsers around.
  873. Note that as a Moo class, we use a subroutine called DEMOLISH that
  874. takes the place of DESTROY; for more information, see
  875. https://metacpan.org/pod/Moo#DEMOLISH.
  876. Usage:
  877. $driver->quit();
  878. =cut
  879. sub quit {
  880. my $self = shift;
  881. my $res = { 'command' => 'quit' };
  882. $self->_execute_command($res);
  883. $self->session_id(undef);
  884. }
  885. =head2 get_current_window_handle
  886. Description:
  887. Retrieve the current window handle.
  888. Output:
  889. STRING - the window handle
  890. Usage:
  891. print $driver->get_current_window_handle();
  892. =cut
  893. sub get_current_window_handle {
  894. my $self = shift;
  895. my $res = { 'command' => 'getCurrentWindowHandle' };
  896. return $self->_execute_command($res);
  897. }
  898. =head2 get_window_handles
  899. Description:
  900. Retrieve the list of window handles used in the session.
  901. Output:
  902. ARRAY of STRING - list of the window handles
  903. Usage:
  904. print Dumper $driver->get_window_handles;
  905. or
  906. # get popup, close, then back
  907. my $handles = $driver->get_window_handles;
  908. $driver->switch_to_window($handles->[1]);
  909. $driver->close;
  910. $driver->switch_to_window($handles->[0]);
  911. =cut
  912. sub get_window_handles {
  913. my $self = shift;
  914. my $res = { 'command' => 'getWindowHandles' };
  915. return $self->_execute_command($res);
  916. }
  917. =head2 get_window_size
  918. Description:
  919. Retrieve the window size
  920. Input:
  921. STRING - <optional> - window handle (default is 'current' window)
  922. Output:
  923. HASH - containing keys 'height' & 'width'
  924. Usage:
  925. my $window_size = $driver->get_window_size();
  926. print $window_size->{'height'}, $window_size->('width');
  927. =cut
  928. sub get_window_size {
  929. my ( $self, $window ) = @_;
  930. $window = ( defined $window ) ? $window : 'current';
  931. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  932. return $self->_execute_command($res);
  933. }
  934. =head2 get_window_position
  935. Description:
  936. Retrieve the window position
  937. Input:
  938. STRING - <optional> - window handle (default is 'current' window)
  939. Output:
  940. HASH - containing keys 'x' & 'y'
  941. Usage:
  942. my $window_size = $driver->get_window_position();
  943. print $window_size->{'x'}, $window_size->('y');
  944. =cut
  945. sub get_window_position {
  946. my ( $self, $window ) = @_;
  947. $window = ( defined $window ) ? $window : 'current';
  948. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  949. return $self->_execute_command($res);
  950. }
  951. =head2 get_current_url
  952. Description:
  953. Retrieve the url of the current page
  954. Output:
  955. STRING - url
  956. Usage:
  957. print $driver->get_current_url();
  958. =cut
  959. sub get_current_url {
  960. my $self = shift;
  961. my $res = { 'command' => 'getCurrentUrl' };
  962. return $self->_execute_command($res);
  963. }
  964. =head2 navigate
  965. Description:
  966. Navigate to a given url. This is same as get() method.
  967. Input:
  968. STRING - url
  969. Usage:
  970. $driver->navigate('http://www.google.com');
  971. =cut
  972. sub navigate {
  973. my ( $self, $url ) = @_;
  974. $self->get($url);
  975. }
  976. =head2 get
  977. Description:
  978. Navigate to a given url
  979. Input:
  980. STRING - url
  981. Usage:
  982. $driver->get('http://www.google.com');
  983. =cut
  984. sub get {
  985. my ( $self, $url ) = @_;
  986. if ($self->has_base_url && $url !~ m|://|) {
  987. $url =~ s|^/||;
  988. $url = $self->base_url . "/" . $url;
  989. }
  990. my $res = { 'command' => 'get' };
  991. my $params = { 'url' => $url };
  992. return $self->_execute_command( $res, $params );
  993. }
  994. =head2 get_title
  995. Description:
  996. Get the current page title
  997. Output:
  998. STRING - Page title
  999. Usage:
  1000. print $driver->get_title();
  1001. =cut
  1002. sub get_title {
  1003. my $self = shift;
  1004. my $res = { 'command' => 'getTitle' };
  1005. return $self->_execute_command($res);
  1006. }
  1007. =head2 go_back
  1008. Description:
  1009. Equivalent to hitting the back button on the browser.
  1010. Usage:
  1011. $driver->go_back();
  1012. =cut
  1013. sub go_back {
  1014. my $self = shift;
  1015. my $res = { 'command' => 'goBack' };
  1016. return $self->_execute_command($res);
  1017. }
  1018. =head2 go_forward
  1019. Description:
  1020. Equivalent to hitting the forward button on the browser.
  1021. Usage:
  1022. $driver->go_forward();
  1023. =cut
  1024. sub go_forward {
  1025. my $self = shift;
  1026. my $res = { 'command' => 'goForward' };
  1027. return $self->_execute_command($res);
  1028. }
  1029. =head2 refresh
  1030. Description:
  1031. Reload the current page.
  1032. Usage:
  1033. $driver->refresh();
  1034. =cut
  1035. sub refresh {
  1036. my $self = shift;
  1037. my $res = { 'command' => 'refresh' };
  1038. return $self->_execute_command($res);
  1039. }
  1040. =head2 javascript
  1041. Description:
  1042. returns true if javascript is enabled in the driver.
  1043. Usage:
  1044. if ($driver->has_javascript) { ...; }
  1045. =cut
  1046. sub has_javascript {
  1047. my $self = shift;
  1048. return int($self->javascript);
  1049. }
  1050. =head2 execute_async_script
  1051. Description:
  1052. Inject a snippet of JavaScript into the page for execution in the context
  1053. of the currently selected frame. The executed script is assumed to be
  1054. asynchronous and must signal that is done by invoking the provided
  1055. callback, which is always provided as the final argument to the function.
  1056. The value to this callback will be returned to the client.
  1057. Asynchronous script commands may not span page loads. If an unload event
  1058. is fired while waiting for a script result, an error should be returned
  1059. to the client.
  1060. Input: 2 (1 optional)
  1061. Required:
  1062. STRING - Javascript to execute on the page
  1063. Optional:
  1064. ARRAY - list of arguments that need to be passed to the script.
  1065. Output:
  1066. {*} - Varied, depending on the type of result expected back from the script.
  1067. Usage:
  1068. my $script = q{
  1069. var arg1 = arguments[0];
  1070. var callback = arguments[arguments.length-1];
  1071. var elem = window.document.findElementById(arg1);
  1072. callback(elem);
  1073. };
  1074. my $elem = $driver->execute_async_script($script,'myid');
  1075. $elem->click;
  1076. =cut
  1077. sub execute_async_script {
  1078. my ( $self, $script, @args ) = @_;
  1079. if ( $self->has_javascript ) {
  1080. if ( not defined $script ) {
  1081. croak 'No script provided';
  1082. }
  1083. my $res = { 'command' => 'executeAsyncScript' };
  1084. # Check the args array if the elem obj is provided & replace it with
  1085. # JSON representation
  1086. for ( my $i = 0; $i < @args; $i++ ) {
  1087. if ( Scalar::Util::blessed( $args[$i] )
  1088. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1089. {
  1090. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1091. }
  1092. }
  1093. my $params = { 'script' => $script, 'args' => \@args };
  1094. my $ret = $self->_execute_command( $res, $params );
  1095. # replace any ELEMENTS with WebElement
  1096. if ( ref($ret)
  1097. and ( ref($ret) eq 'HASH' )
  1098. and exists $ret->{'ELEMENT'} )
  1099. {
  1100. $ret = $self->webelement_class->new( id => $ret->{ELEMENT},
  1101. driver => $self );
  1102. }
  1103. return $ret;
  1104. }
  1105. else {
  1106. croak 'Javascript is not enabled on remote driver instance.';
  1107. }
  1108. }
  1109. =head2 execute_script
  1110. Description:
  1111. Inject a snippet of JavaScript into the page and return its result.
  1112. WebElements that should be passed to the script as an argument should be
  1113. specified in the arguments array as WebElement object. Likewise,
  1114. any WebElements in the script result will be returned as WebElement object.
  1115. Input: 2 (1 optional)
  1116. Required:
  1117. STRING - Javascript to execute on the page
  1118. Optional:
  1119. ARRAY - list of arguments that need to be passed to the script.
  1120. Output:
  1121. {*} - Varied, depending on the type of result expected back from the script.
  1122. Usage:
  1123. my $script = q{
  1124. var arg1 = arguments[0];
  1125. var elem = window.document.findElementById(arg1);
  1126. return elem;
  1127. };
  1128. my $elem = $driver->execute_script($script,'myid');
  1129. $elem->click;
  1130. =cut
  1131. sub execute_script {
  1132. my ( $self, $script, @args ) = @_;
  1133. if ( $self->has_javascript ) {
  1134. if ( not defined $script ) {
  1135. croak 'No script provided';
  1136. }
  1137. my $res = { 'command' => 'executeScript' };
  1138. # Check the args array if the elem obj is provided & replace it with
  1139. # JSON representation
  1140. for ( my $i = 0; $i < @args; $i++ ) {
  1141. if ( Scalar::Util::blessed( $args[$i] )
  1142. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1143. {
  1144. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1145. }
  1146. }
  1147. my $params = { 'script' => $script, 'args' => [@args] };
  1148. my $ret = $self->_execute_command( $res, $params );
  1149. return $self->_convert_to_webelement($ret);
  1150. }
  1151. else {
  1152. croak 'Javascript is not enabled on remote driver instance.';
  1153. }
  1154. }
  1155. # _convert_to_webelement
  1156. # An internal method used to traverse a data structure
  1157. # and convert any ELEMENTS with WebElements
  1158. sub _convert_to_webelement {
  1159. my ( $self, $ret ) = @_;
  1160. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  1161. if ( ( keys %$ret == 1 ) and exists $ret->{'ELEMENT'} ) {
  1162. # replace an ELEMENT with WebElement
  1163. return $self->webelement_class->new( id => $ret->{ELEMENT},
  1164. driver => $self );
  1165. }
  1166. my %hash;
  1167. foreach my $key ( keys %$ret ) {
  1168. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1169. }
  1170. return \%hash;
  1171. }
  1172. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1173. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1174. return \@array;
  1175. }
  1176. return $ret;
  1177. }
  1178. =head2 screenshot
  1179. Description:
  1180. Get a screenshot of the current page as a base64 encoded image.
  1181. Output:
  1182. STRING - base64 encoded image
  1183. Usage:
  1184. print $driver->screenshot();
  1185. To conveniently write the screenshot to a file, see L<capture_screenshot()>.
  1186. =cut
  1187. sub screenshot {
  1188. my ($self) = @_;
  1189. my $res = { 'command' => 'screenshot' };
  1190. return $self->_execute_command($res);
  1191. }
  1192. =head2 capture_screenshot
  1193. Description:
  1194. Capture a screenshot and save as a PNG to provided file name.
  1195. (The method is compatible with the WWW::Selenium method of the same name)
  1196. Output:
  1197. TRUE - (Screenshot is written to file)
  1198. Usage:
  1199. $driver->capture_screenshot($filename);
  1200. =cut
  1201. sub capture_screenshot {
  1202. my ( $self, $filename ) = @_;
  1203. croak '$filename is required' unless $filename;
  1204. open( my $fh, '>', $filename );
  1205. binmode $fh;
  1206. print $fh MIME::Base64::decode_base64( $self->screenshot() );
  1207. CORE::close $fh;
  1208. return 1;
  1209. }
  1210. =head2 available_engines
  1211. Description:
  1212. List all available engines on the machine. To use an engine, it has to be present in this list.
  1213. Output:
  1214. {Array.<string>} A list of available engines
  1215. Usage:
  1216. print Dumper $driver->available_engines;
  1217. =cut
  1218. sub available_engines {
  1219. my ($self) = @_;
  1220. my $res = { 'command' => 'availableEngines' };
  1221. return $self->_execute_command($res);
  1222. }
  1223. =head2 switch_to_frame
  1224. Description:
  1225. Change focus to another frame on the page. If the frame ID is null, the
  1226. server will switch to the page's default content. You can also switch to a
  1227. WebElement, for e.g. you can find an iframe using find_element & then
  1228. provide that as an input to this method. Also see e.g.
  1229. Input: 1
  1230. Required:
  1231. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1232. mentioned.
  1233. Usage:
  1234. $driver->switch_to_frame('frame_1');
  1235. or
  1236. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1237. =cut
  1238. sub switch_to_frame {
  1239. my ( $self, $id ) = @_;
  1240. my $json_null = JSON::null;
  1241. my $params;
  1242. $id = ( defined $id ) ? $id : $json_null;
  1243. my $res = { 'command' => 'switchToFrame' };
  1244. if ( ref $id eq $self->webelement_class ) {
  1245. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1246. }
  1247. else {
  1248. $params = { 'id' => $id };
  1249. }
  1250. return $self->_execute_command( $res, $params );
  1251. }
  1252. =head2 switch_to_window
  1253. Description:
  1254. Change focus to another window. The window to change focus to may
  1255. be specified by its server assigned window handle, or by the value
  1256. of the page's window.name attribute.
  1257. If you wish to use the window name as the target, you'll need to
  1258. have set C<window.name> on the page either in app code or via
  1259. L</execute_script>, or pass a name as the second argument to the
  1260. C<window.open()> function when opening the new window. Note that
  1261. the window name used here has nothing to do with the window title,
  1262. or the C<< <title> >> element on the page.
  1263. Otherwise, use L</get_window_handles> and select a
  1264. Webdriver-generated handle from the output of that function.
  1265. Input: 1
  1266. Required:
  1267. STRING - Window handle or the Window name
  1268. Usage:
  1269. $driver->switch_to_window('MY Homepage');
  1270. or
  1271. # close a popup window and switch back
  1272. my $handles = $driver->get_window_handles;
  1273. $driver->switch_to_window($handles->[1]);
  1274. $driver->close;
  1275. $driver->switch_to_window($handles->[0]);
  1276. =cut
  1277. sub switch_to_window {
  1278. my ( $self, $name ) = @_;
  1279. if ( not defined $name ) {
  1280. return 'Window name not provided';
  1281. }
  1282. my $res = { 'command' => 'switchToWindow' };
  1283. my $params = { 'name' => $name };
  1284. return $self->_execute_command( $res, $params );
  1285. }
  1286. =head2 get_speed
  1287. Description:
  1288. DEPRECATED - this function is a no-op in Webdriver, and will be
  1289. removed in the upcoming version of this module. See
  1290. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion
  1291. and
  1292. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1293. =cut
  1294. sub get_speed {
  1295. carp 'get_speed is deprecated and will be removed in the upcoming version of this module';
  1296. }
  1297. =head2 set_speed
  1298. Description:
  1299. DEPRECATED - this function is a no-op in Webdriver, and will be
  1300. removed in the upcoming version of this module. See
  1301. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion
  1302. and
  1303. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1304. =cut
  1305. sub set_speed {
  1306. carp 'set_speed is deprecated and will be removed in the upcoming version of this module';
  1307. }
  1308. =head2 set_window_position
  1309. Description:
  1310. Set the position (on screen) where you want your browser to be displayed.
  1311. Input:
  1312. INT - x co-ordinate
  1313. INT - y co-ordinate
  1314. STRING - <optional> - window handle (default is 'current' window)
  1315. Output:
  1316. BOOLEAN - Success or failure
  1317. Usage:
  1318. $driver->set_window_position(50, 50);
  1319. =cut
  1320. sub set_window_position {
  1321. my ( $self, $x, $y, $window ) = @_;
  1322. $window = ( defined $window ) ? $window : 'current';
  1323. if ( not defined $x and not defined $y ) {
  1324. croak "X & Y co-ordinates are required";
  1325. }
  1326. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1327. my $params = { 'x' => $x, 'y' => $y };
  1328. my $ret = $self->_execute_command( $res, $params );
  1329. return $ret ? 1 : 0;
  1330. }
  1331. =head2 set_window_size
  1332. Description:
  1333. Set the size of the browser window
  1334. Input:
  1335. INT - height of the window
  1336. INT - width of the window
  1337. STRING - <optional> - window handle (default is 'current' window)
  1338. Output:
  1339. BOOLEAN - Success or failure
  1340. Usage:
  1341. $driver->set_window_size(640, 480);
  1342. =cut
  1343. sub set_window_size {
  1344. my ( $self, $height, $width, $window ) = @_;
  1345. $window = ( defined $window ) ? $window : 'current';
  1346. if ( not defined $height and not defined $width ) {
  1347. croak "height & width of browser are required";
  1348. }
  1349. $height += 0;
  1350. $width += 0;
  1351. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1352. my $params = { 'height' => $height, 'width' => $width };
  1353. my $ret = $self->_execute_command( $res, $params );
  1354. return $ret ? 1 : 0;
  1355. }
  1356. =head2 maximize_window
  1357. Description:
  1358. Maximizes the browser window
  1359. Input:
  1360. STRING - <optional> - window handle (default is 'current' window)
  1361. Output:
  1362. BOOLEAN - Success or failure
  1363. Usage:
  1364. $driver->maximize_window();
  1365. =cut
  1366. sub maximize_window {
  1367. my ( $self, $window ) = @_;
  1368. $window = ( defined $window ) ? $window : 'current';
  1369. my $res = { 'command' => 'maximizeWindow', 'window_handle' => $window };
  1370. my $ret = $self->_execute_command( $res );
  1371. return $ret ? 1 : 0;
  1372. }
  1373. =head2 get_all_cookies
  1374. Description:
  1375. Retrieve all cookies visible to the current page. Each cookie will be
  1376. returned as a HASH reference with the following keys & their value types:
  1377. 'name' - STRING
  1378. 'value' - STRING
  1379. 'path' - STRING
  1380. 'domain' - STRING
  1381. 'secure' - BOOLEAN
  1382. Output:
  1383. ARRAY of HASHES - list of all the cookie hashes
  1384. Usage:
  1385. print Dumper($driver->get_all_cookies());
  1386. =cut
  1387. sub get_all_cookies {
  1388. my ($self) = @_;
  1389. my $res = { 'command' => 'getAllCookies' };
  1390. return $self->_execute_command($res);
  1391. }
  1392. =head2 add_cookie
  1393. Description:
  1394. Set a cookie on the domain.
  1395. Input: 5 (1 optional)
  1396. Required:
  1397. 'name' - STRING
  1398. 'value' - STRING
  1399. 'path' - STRING
  1400. 'domain' - STRING
  1401. Optional:
  1402. 'secure' - BOOLEAN - default is false.
  1403. Usage:
  1404. $driver->add_cookie('foo', 'bar', '/', '.google.com', 0)
  1405. =cut
  1406. sub add_cookie {
  1407. my ( $self, $name, $value, $path, $domain, $secure ) = @_;
  1408. if ( ( not defined $name )
  1409. || ( not defined $value )
  1410. || ( not defined $path )
  1411. || ( not defined $domain ) )
  1412. {
  1413. croak "Missing parameters";
  1414. }
  1415. my $res = { 'command' => 'addCookie' };
  1416. my $json_false = JSON::false;
  1417. my $json_true = JSON::true;
  1418. $secure = ( defined $secure && $secure ) ? $json_true : $json_false;
  1419. my $params = {
  1420. 'cookie' => {
  1421. 'name' => $name,
  1422. 'value' => $value,
  1423. 'path' => $path,
  1424. 'domain' => $domain,
  1425. 'secure' => $secure,
  1426. }
  1427. };
  1428. return $self->_execute_command( $res, $params );
  1429. }
  1430. =head2 delete_all_cookies
  1431. Description:
  1432. Delete all cookies visible to the current page.
  1433. Usage:
  1434. $driver->delete_all_cookies();
  1435. =cut
  1436. sub delete_all_cookies {
  1437. my ($self) = @_;
  1438. my $res = { 'command' => 'deleteAllCookies' };
  1439. return $self->_execute_command($res);
  1440. }
  1441. =head2 delete_cookie_named
  1442. Description:
  1443. Delete the cookie with the given name. This command will be a no-op if there
  1444. is no such cookie visible to the current page.
  1445. Input: 1
  1446. Required:
  1447. STRING - name of cookie to delete
  1448. Usage:
  1449. $driver->delete_cookie_named('foo');
  1450. =cut
  1451. sub delete_cookie_named {
  1452. my ( $self, $cookie_name ) = @_;
  1453. if ( not defined $cookie_name ) {
  1454. croak "Cookie name not provided";
  1455. }
  1456. my $res = { 'command' => 'deleteCookieNamed', 'name' => $cookie_name };
  1457. return $self->_execute_command($res);
  1458. }
  1459. =head2 get_page_source
  1460. Description:
  1461. Get the current page source.
  1462. Output:
  1463. STRING - The page source.
  1464. Usage:
  1465. print $driver->get_page_source();
  1466. =cut
  1467. sub get_page_source {
  1468. my ($self) = @_;
  1469. my $res = { 'command' => 'getPageSource' };
  1470. return $self->_execute_command($res);
  1471. }
  1472. =head2 find_element
  1473. Description:
  1474. Search for an element on the page, starting from the document
  1475. root. The located element will be returned as a WebElement
  1476. object. If the element cannot be found, we will CROAK, killing
  1477. your script. If you wish for a warning instead, use the
  1478. parameterized version of the finders:
  1479. find_element_by_class
  1480. find_element_by_class_name
  1481. find_element_by_css
  1482. find_element_by_id
  1483. find_element_by_link
  1484. find_element_by_link_text
  1485. find_element_by_name
  1486. find_element_by_partial_link_text
  1487. find_element_by_tag_name
  1488. find_element_by_xpath
  1489. These functions all take a single STRING argument: the locator
  1490. search target of the element you want. If the element is found, we
  1491. will receive a WebElement. Otherwise, we will return 0. Note that
  1492. invoking methods on 0 will of course kill your script.
  1493. Input: 2 (1 optional)
  1494. Required:
  1495. STRING - The search target.
  1496. Optional:
  1497. STRING - Locator scheme to use to search the element, available schemes:
  1498. {class, class_name, css, id, link, link_text, partial_link_text,
  1499. tag_name, name, xpath}
  1500. Defaults to 'xpath' if not configured global during instantiation.
  1501. Output:
  1502. Selenium::Remote::WebElement - WebElement Object
  1503. (This could be a subclass of L<Selenium::Remote::WebElement> if C<webelement_class> was set.
  1504. Usage:
  1505. $driver->find_element("//input[\@name='q']");
  1506. =cut
  1507. sub find_element {
  1508. my ( $self, $query, $method ) = @_;
  1509. if ( not defined $query ) {
  1510. croak 'Search string to find element not provided.';
  1511. }
  1512. my $using =
  1513. ( defined $method ) ? $self->FINDERS->{$method} : $self->default_finder;
  1514. if ( defined $using ) {
  1515. my $res = { 'command' => 'findElement' };
  1516. my $params = { 'using' => $using, 'value' => $query };
  1517. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1518. if ($@) {
  1519. if ( $@
  1520. =~ /(An element could not be located on the page using the given search parameters)/
  1521. )
  1522. {
  1523. # give details on what element wasn't found
  1524. $@ = "$1: $query,$using";
  1525. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1526. croak $@;
  1527. }
  1528. else {
  1529. # re throw if the exception wasn't what we expected
  1530. die $@;
  1531. }
  1532. }
  1533. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1534. driver => $self );
  1535. }
  1536. else {
  1537. croak "Bad method, expected: " . join(', ', keys %{ $self->FINDERS });
  1538. }
  1539. }
  1540. =head2 find_elements
  1541. Description:
  1542. Search for multiple elements on the page, starting from the document root.
  1543. The located elements will be returned as an array of WebElement object.
  1544. Input: 2 (1 optional)
  1545. Required:
  1546. STRING - The search target.
  1547. Optional:
  1548. STRING - Locator scheme to use to search the element, available schemes:
  1549. {class, class_name, css, id, link, link_text, partial_link_text,
  1550. tag_name, name, xpath}
  1551. Defaults to 'xpath' if not configured global during instantiation.
  1552. Output:
  1553. ARRAY or ARRAYREF of WebElement Objects
  1554. Usage:
  1555. $driver->find_elements("//input");
  1556. =cut
  1557. sub find_elements {
  1558. my ( $self, $query, $method ) = @_;
  1559. if ( not defined $query ) {
  1560. croak 'Search string to find element not provided.';
  1561. }
  1562. my $using =
  1563. ( defined $method ) ? $self->FINDERS->{$method} : $self->default_finder;
  1564. if ( defined $using ) {
  1565. my $res = { 'command' => 'findElements' };
  1566. my $params = { 'using' => $using, 'value' => $query };
  1567. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1568. if ($@) {
  1569. if ( $@
  1570. =~ /(An element could not be located on the page using the given search parameters)/
  1571. )
  1572. {
  1573. # give details on what element wasn't found
  1574. $@ = "$1: $query,$using";
  1575. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1576. croak $@;
  1577. }
  1578. else {
  1579. # re throw if the exception wasn't what we expected
  1580. die $@;
  1581. }
  1582. }
  1583. my $elem_obj_arr = [];
  1584. foreach (@$ret_data) {
  1585. push(
  1586. @$elem_obj_arr,
  1587. $self->webelement_class->new(
  1588. id => $_->{ELEMENT}, driver => $self
  1589. )
  1590. );
  1591. }
  1592. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1593. }
  1594. else {
  1595. croak "Bad method, expected: " . join(', ', keys %{ $self->FINDERS });
  1596. }
  1597. }
  1598. =head2 find_child_element
  1599. Description:
  1600. Search for an element on the page, starting from the identified element. The
  1601. located element will be returned as a WebElement object.
  1602. Input: 3 (1 optional)
  1603. Required:
  1604. Selenium::Remote::WebElement - WebElement object from where you want to
  1605. start searching.
  1606. STRING - The search target. (Do not use a double whack('//')
  1607. in an xpath to search for a child element
  1608. ex: '//option[@id="something"]'
  1609. instead use a dot whack ('./')
  1610. ex: './option[@id="something"]')
  1611. Optional:
  1612. STRING - Locator scheme to use to search the element, available schemes:
  1613. {class, class_name, css, id, link, link_text, partial_link_text,
  1614. tag_name, name, xpath}
  1615. Defaults to 'xpath' if not configured global during instantiation.
  1616. Output:
  1617. WebElement Object
  1618. Usage:
  1619. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1620. # note the usage of ./ when searching for a child element instead of //
  1621. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1622. =cut
  1623. sub find_child_element {
  1624. my ( $self, $elem, $query, $method ) = @_;
  1625. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1626. croak "Missing parameters";
  1627. }
  1628. my $using =
  1629. ( defined $method ) ? $self->FINDERS->{$method} : $self->default_finder;
  1630. if ( defined $using ) {
  1631. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1632. my $params = { 'using' => $using, 'value' => $query };
  1633. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1634. if ($@) {
  1635. if ( $@
  1636. =~ /(An element could not be located on the page using the given search parameters)/
  1637. )
  1638. {
  1639. # give details on what element wasn't found
  1640. $@ = "$1: $query,$using";
  1641. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1642. croak $@;
  1643. }
  1644. else {
  1645. # re throw if the exception wasn't what we expected
  1646. die $@;
  1647. }
  1648. }
  1649. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1650. driver => $self );
  1651. }
  1652. else {
  1653. croak "Bad method, expected: " . join(', ', keys %{ $self->FINDERS });
  1654. }
  1655. }
  1656. =head2 find_child_elements
  1657. Description:
  1658. Search for multiple element on the page, starting from the identified
  1659. element. The located elements will be returned as an array of WebElement
  1660. objects.
  1661. Input: 3 (1 optional)
  1662. Required:
  1663. Selenium::Remote::WebElement - WebElement object from where you want to
  1664. start searching.
  1665. STRING - The search target.
  1666. Optional:
  1667. STRING - Locator scheme to use to search the element, available schemes:
  1668. {class, class_name, css, id, link, link_text, partial_link_text,
  1669. tag_name, name, xpath}
  1670. Defaults to 'xpath' if not configured global during instantiation.
  1671. Output:
  1672. ARRAY of WebElement Objects.
  1673. Usage:
  1674. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1675. # note the usage of ./ when searching for a child element instead of //
  1676. my $child = $driver->find_child_elements($elem1, "./option");
  1677. =cut
  1678. sub find_child_elements {
  1679. my ( $self, $elem, $query, $method ) = @_;
  1680. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1681. croak "Missing parameters";
  1682. }
  1683. my $using =
  1684. ( defined $method ) ? $self->FINDERS->{$method} : $self->default_finder;
  1685. if ( defined $using ) {
  1686. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1687. my $params = { 'using' => $using, 'value' => $query };
  1688. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1689. if ($@) {
  1690. if ( $@
  1691. =~ /(An element could not be located on the page using the given search parameters)/
  1692. )
  1693. {
  1694. # give details on what element wasn't found
  1695. $@ = "$1: $query,$using";
  1696. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1697. croak $@;
  1698. }
  1699. else {
  1700. # re throw if the exception wasn't what we expected
  1701. die $@;
  1702. }
  1703. }
  1704. my $elem_obj_arr = [];
  1705. my $i = 0;
  1706. foreach (@$ret_data) {
  1707. $elem_obj_arr->[$i] =
  1708. $self->webelement_class->new( id => $_->{ELEMENT},
  1709. driver => $self );
  1710. $i++;
  1711. }
  1712. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1713. }
  1714. else {
  1715. croak "Bad method, expected: " . join(', ', keys %{ $self->FINDERS });
  1716. }
  1717. }
  1718. =head2 find_element_by_class
  1719. See L</find_element>.
  1720. =head2 find_element_by_class_name
  1721. See L</find_element>.
  1722. =head2 find_element_by_css
  1723. See L</find_element>.
  1724. =head2 find_element_by_id
  1725. See L</find_element>.
  1726. =head2 find_element_by_link
  1727. See L</find_element>.
  1728. =head2 find_element_by_link_text
  1729. See L</find_element>.
  1730. =head2 find_element_by_name
  1731. See L</find_element>.
  1732. =head2 find_element_by_partial_link_text
  1733. See L</find_element>.
  1734. =head2 find_element_by_tag_name
  1735. See L</find_element>.
  1736. =head2 find_element_by_xpath
  1737. See L</find_element>.
  1738. =head2 get_active_element
  1739. Description:
  1740. Get the element on the page that currently has focus.. The located element
  1741. will be returned as a WebElement object.
  1742. Output:
  1743. WebElement Object
  1744. Usage:
  1745. $driver->get_active_element();
  1746. =cut
  1747. sub get_active_element {
  1748. my ($self) = @_;
  1749. my $res = { 'command' => 'getActiveElement' };
  1750. my $ret_data = eval { $self->_execute_command($res) };
  1751. if ($@) {
  1752. croak $@;
  1753. }
  1754. else {
  1755. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1756. driver => $self );
  1757. }
  1758. }
  1759. =head2 cache_status
  1760. Description:
  1761. Get the status of the html5 application cache.
  1762. Usage:
  1763. print $driver->cache_status;
  1764. Output:
  1765. <number> - Status code for application cache: {UNCACHED = 0, IDLE = 1, CHECKING = 2, DOWNLOADING = 3, UPDATE_READY = 4, OBSOLETE = 5}
  1766. =cut
  1767. sub cache_status {
  1768. my ($self) = @_;
  1769. my $res = { 'command' => 'cacheStatus' };
  1770. return $self->_execute_command($res);
  1771. }
  1772. =head2 set_geolocation
  1773. Description:
  1774. Set the current geographic location - note that your driver must
  1775. implement this endpoint, or else it will crash your session. At the
  1776. very least, it works in v2.12 of Chromedriver.
  1777. Input:
  1778. Required:
  1779. HASH: A hash with key C<location> whose value is a Location hashref. See
  1780. usage section for example.
  1781. Usage:
  1782. $driver->set_geolocation( location => {
  1783. latitude => 40.714353,
  1784. longitude => -74.005973,
  1785. altitude => 0.056747
  1786. });
  1787. Output:
  1788. BOOLEAN - success or failure
  1789. =cut
  1790. sub set_geolocation {
  1791. my ( $self, %params ) = @_;
  1792. my $res = { 'command' => 'setGeolocation' };
  1793. return $self->_execute_command( $res, \%params );
  1794. }
  1795. =head2 get_geolocation
  1796. Description:
  1797. Get the current geographic location. Note that your webdriver must
  1798. implement this endpoint - otherwise, it will crash your session. At
  1799. the time of release, we couldn't get this to work on the desktop
  1800. FirefoxDriver or desktop Chromedriver.
  1801. Usage:
  1802. print $driver->get_geolocation;
  1803. Output:
  1804. { latitude: number, longitude: number, altitude: number } - The current geo location.
  1805. =cut
  1806. sub get_geolocation {
  1807. my ($self) = @_;
  1808. my $res = { 'command' => 'getGeolocation' };
  1809. return $self->_execute_command($res);
  1810. }
  1811. =head2 get_log
  1812. Description:
  1813. Get the log for a given log type. Log buffer is reset after each request.
  1814. Input:
  1815. Required:
  1816. <STRING> - Type of log to retrieve:
  1817. {client|driver|browser|server}. There may be others available; see
  1818. get_log_types for a full list for your driver.
  1819. Usage:
  1820. $driver->get_log( $log_type );
  1821. Output:
  1822. <ARRAY|ARRAYREF> - An array of log entries since the most recent request.
  1823. =cut
  1824. sub get_log {
  1825. my ( $self, $type ) = @_;
  1826. my $res = { 'command' => 'getLog' };
  1827. return $self->_execute_command( $res, { type => $type });
  1828. }
  1829. =head2 get_log_types
  1830. Description:
  1831. Get available log types. By default, every driver should have client,
  1832. driver, browser, and server types, but there may be more available,
  1833. depending on your driver.
  1834. Usage:
  1835. my @types = $driver->get_log_types;
  1836. $driver->get_log($types[0]);
  1837. Output:
  1838. <ARRAYREF> - The list of log types.
  1839. =cut
  1840. sub get_log_types {
  1841. my ($self) = @_;
  1842. my $res = { 'command' => 'getLogTypes' };
  1843. return $self->_execute_command($res);
  1844. }
  1845. =head2 set_orientation
  1846. Description:
  1847. Set the browser orientation.
  1848. Input:
  1849. Required:
  1850. <STRING> - Orientation {LANDSCAPE|PORTRAIT}
  1851. Usage:
  1852. $driver->set_orientation( $orientation );
  1853. Output:
  1854. BOOLEAN - success or failure
  1855. =cut
  1856. sub set_orientation {
  1857. my ( $self, $orientation ) = @_;
  1858. my $res = { 'command' => 'setOrientation' };
  1859. return $self->_execute_command( $res, { orientation => $orientation } );
  1860. }
  1861. =head2 get_orientation
  1862. Description:
  1863. Get the current browser orientation. Returns either LANDSCAPE|PORTRAIT.
  1864. Usage:
  1865. print $driver->get_orientation;
  1866. Output:
  1867. <STRING> - your orientation.
  1868. =cut
  1869. sub get_orientation {
  1870. my ($self) = @_;
  1871. my $res = { 'command' => 'getOrientation' };
  1872. return $self->_execute_command($res);
  1873. }
  1874. =head2 send_modifier
  1875. Description:
  1876. Send an event to the active element to depress or release a modifier key.
  1877. Input: 2
  1878. Required:
  1879. 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
  1880. isdown - Boolean/String - Whether to generate a key down or key up
  1881. Usage:
  1882. $driver->send_modifier('Alt','down');
  1883. $elem->send_keys('c');
  1884. $driver->send_modifier('Alt','up');
  1885. or
  1886. $driver->send_modifier('Alt',1);
  1887. $elem->send_keys('c');
  1888. $driver->send_modifier('Alt',0);
  1889. =cut
  1890. sub send_modifier {
  1891. my ( $self, $modifier, $isdown ) = @_;
  1892. if ( $isdown =~ /(down|up)/ ) {
  1893. $isdown = $isdown =~ /down/ ? 1 : 0;
  1894. }
  1895. my $res = { 'command' => 'sendModifier' };
  1896. my $params = {
  1897. value => $modifier,
  1898. isdown => $isdown
  1899. };
  1900. return $self->_execute_command( $res, $params );
  1901. }
  1902. =head2 compare_elements
  1903. Description:
  1904. Test if two element IDs refer to the same DOM element.
  1905. Input: 2
  1906. Required:
  1907. Selenium::Remote::WebElement - WebElement Object
  1908. Selenium::Remote::WebElement - WebElement Object
  1909. Output:
  1910. BOOLEAN
  1911. Usage:
  1912. $driver->compare_elements($elem_obj1, $elem_obj2);
  1913. =cut
  1914. sub compare_elements {
  1915. my ( $self, $elem1, $elem2 ) = @_;
  1916. my $res = {
  1917. 'command' => 'elementEquals',
  1918. 'id' => $elem1->{id},
  1919. 'other' => $elem2->{id}
  1920. };
  1921. return $self->_execute_command($res);
  1922. }
  1923. =head2 click
  1924. Description:
  1925. Click any mouse button (at the coordinates set by the last moveto command).
  1926. Input:
  1927. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1928. defaults to 'LEFT'
  1929. Usage:
  1930. $driver->click('LEFT');
  1931. $driver->click(1); #MIDDLE
  1932. $driver->click('RIGHT');
  1933. $driver->click; #Defaults to left
  1934. =cut
  1935. sub click {
  1936. my ( $self, $button ) = @_;
  1937. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  1938. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  1939. $button = $button_enum->{ uc $1 };
  1940. }
  1941. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  1942. $button = $1;
  1943. }
  1944. else {
  1945. $button = 0;
  1946. }
  1947. my $res = { 'command' => 'click' };
  1948. my $params = { 'button' => $button };
  1949. return $self->_execute_command( $res, $params );
  1950. }
  1951. =head2 double_click
  1952. Description:
  1953. Double-clicks at the current mouse coordinates (set by moveto).
  1954. Usage:
  1955. $driver->double_click;
  1956. =cut
  1957. sub double_click {
  1958. my ($self) = @_;
  1959. my $res = { 'command' => 'doubleClick' };
  1960. return $self->_execute_command($res);
  1961. }
  1962. =head2 button_down
  1963. Description:
  1964. Click and hold the left mouse button (at the coordinates set by the
  1965. last moveto command). Note that the next mouse-related command that
  1966. should follow is buttonup . Any other mouse command (such as click
  1967. or another call to buttondown) will yield undefined behaviour.
  1968. Usage:
  1969. $self->button_down;
  1970. =cut
  1971. sub button_down {
  1972. my ($self) = @_;
  1973. my $res = { 'command' => 'buttonDown' };
  1974. return $self->_execute_command($res);
  1975. }
  1976. =head2 button_up
  1977. Description:
  1978. Releases the mouse button previously held (where the mouse is
  1979. currently at). Must be called once for every buttondown command
  1980. issued. See the note in click and buttondown about implications of
  1981. out-of-order commands.
  1982. Usage:
  1983. $self->button_up;
  1984. =cut
  1985. sub button_up {
  1986. my ($self) = @_;
  1987. my $res = { 'command' => 'buttonUp' };
  1988. return $self->_execute_command($res);
  1989. }
  1990. =head2 upload_file
  1991. Description:
  1992. Upload a file from the local machine to the selenium server
  1993. machine. That file then can be used for testing file upload on web
  1994. forms. Returns the remote-server's path to the file.
  1995. Passing raw data as an argument past the filename will upload
  1996. that rather than the file's contents.
  1997. When passing raw data, be advised that it expects a zipped
  1998. and then base64 encoded version of a single file.
  1999. Multiple files and/or directories are not supported by the remote server.
  2000. Usage:
  2001. my $remote_fname = $driver->upload_file( $fname );
  2002. my $element = $driver->find_element( '//input[@id="file"]' );
  2003. $element->send_keys( $remote_fname );
  2004. =cut
  2005. # this method duplicates upload() method in the
  2006. # org.openqa.selenium.remote.RemoteWebElement java class.
  2007. sub upload_file {
  2008. my ( $self, $filename, $raw_content ) = @_;
  2009. my $params;
  2010. if (defined $raw_content) {
  2011. #If no processing is passed, send the argument raw
  2012. $params = {
  2013. file => $raw_content
  2014. };
  2015. }
  2016. else {
  2017. #Otherwise, zip/base64 it.
  2018. $params = $self->_prepare_file($filename);
  2019. }
  2020. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  2021. my $ret = $self->_execute_command( $res, $params );
  2022. return $ret;
  2023. }
  2024. sub _prepare_file {
  2025. my ($self,$filename) = @_;
  2026. if ( not -r $filename ) { croak "upload_file: no such file: $filename"; }
  2027. my $string = ""; # buffer
  2028. my $zip = Archive::Zip->new();
  2029. $zip->addFile($filename, basename($filename));
  2030. if ($zip->writeToFileHandle(IO::String->new($string)) != AZ_OK) {
  2031. die 'zip failed';
  2032. }
  2033. return {
  2034. file => MIME::Base64::encode_base64($string) # base64-encoded string
  2035. };
  2036. }
  2037. =head2 get_text
  2038. Description:
  2039. Get the text of a particular element. Wrapper around L<find_element()>
  2040. Usage:
  2041. $text = $driver->get_text("//div[\@name='q']");
  2042. =cut
  2043. sub get_text {
  2044. my $self = shift;
  2045. return $self->find_element(@_)->get_text();
  2046. }
  2047. =head2 get_body
  2048. Description:
  2049. Get the current text for the whole body. If you want the entire raw HTML instead,
  2050. See L<get_page_source>.
  2051. Usage:
  2052. $body_text = $driver->get_body();
  2053. =cut
  2054. sub get_body {
  2055. my $self = shift;
  2056. return $self->get_text('//body', 'xpath');
  2057. }
  2058. =head2 get_path
  2059. Description:
  2060. Get the path part of the current browser location.
  2061. Usage:
  2062. $path = $driver->get_path();
  2063. =cut
  2064. sub get_path {
  2065. my $self = shift;
  2066. my $location = $self->get_current_url;
  2067. $location =~ s/\?.*//; # strip of query params
  2068. $location =~ s/#.*//; # strip of anchors
  2069. $location =~ s#^https?://[^/]+##; # strip off host
  2070. return $location;
  2071. }
  2072. =head2 get_user_agent
  2073. Description:
  2074. Convenience method to get the user agent string, according to the
  2075. browser's value for window.navigator.userAgent.
  2076. Usage:
  2077. $user_agent = $driver->get_user_agent()
  2078. =cut
  2079. sub get_user_agent {
  2080. my $self = shift;
  2081. return $self->execute_script('return window.navigator.userAgent;');
  2082. }
  2083. =head2 set_inner_window_size
  2084. Description:
  2085. Set the inner window size by closing the current window and
  2086. reopening the current page in a new window. This can be useful
  2087. when using browsers to mock as mobile devices.
  2088. This sub will be fired automatically if you set the
  2089. C<inner_window_size> hash key option during instantiation.
  2090. Input:
  2091. INT - height of the window
  2092. INT - width of the window
  2093. Output:
  2094. BOOLEAN - Success or failure
  2095. Usage:
  2096. $driver->set_inner_window_size(640, 480)
  2097. =cut
  2098. sub set_inner_window_size {
  2099. my $self = shift;
  2100. my $height = shift;
  2101. my $width = shift;
  2102. my $location = $self->get_current_url;
  2103. $self->execute_script('window.open("' . $location . '", "_blank")');
  2104. $self->close;
  2105. my @handles = @{ $self->get_window_handles };
  2106. $self->switch_to_window(pop @handles);
  2107. my @resize = (
  2108. 'window.innerHeight = ' . $height,
  2109. 'window.innerWidth = ' . $width,
  2110. 'return 1'
  2111. );
  2112. return $self->execute_script(join(';', @resize)) ? 1 : 0;
  2113. }
  2114. =head2 get_local_storage_item
  2115. Description:
  2116. Get the value of a local storage item specified by the given key.
  2117. Input: 1
  2118. Required:
  2119. STRING - name of the key to be retrieved
  2120. Output:
  2121. STRING - value of the local storage item
  2122. Usage:
  2123. $driver->get_local_storage_item('key')
  2124. =cut
  2125. sub get_local_storage_item {
  2126. my ($self, $key) = @_;
  2127. my $res = { 'command' => 'getLocalStorageItem' };
  2128. my $params = { 'key' => $key };
  2129. return $self->_execute_command($res, $params);
  2130. }
  2131. =head2 delete_local_storage_item
  2132. Description:
  2133. Get the value of a local storage item specified by the given key.
  2134. Input: 1
  2135. Required
  2136. STRING - name of the key to be deleted
  2137. Usage:
  2138. $driver->delete_local_storage_item('key')
  2139. =cut
  2140. sub delete_local_storage_item {
  2141. my ($self, $key) = @_;
  2142. my $res = { 'command' => 'deleteLocalStorageItem' };
  2143. my $params = { 'key' => $key };
  2144. return $self->_execute_command($res, $params);
  2145. }
  2146. sub _coerce_timeout_ms {
  2147. my ($ms) = @_;
  2148. if ( defined $ms ) {
  2149. return _coerce_number( $ms );
  2150. }
  2151. else {
  2152. croak 'Expecting a timeout in ms';
  2153. }
  2154. }
  2155. sub _coerce_number {
  2156. my ($maybe_number) = @_;
  2157. if ( Scalar::Util::looks_like_number( $maybe_number )) {
  2158. return $maybe_number + 0;
  2159. }
  2160. else {
  2161. croak "Expecting a number, not: $maybe_number";
  2162. }
  2163. }
  2164. 1;
  2165. __END__
  2166. =head1 SEE ALSO
  2167. http://code.google.com/p/selenium/
  2168. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  2169. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  2170. Brownie
  2171. Wight
  2172. =cut