Driver.pm 77 KB

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