1
0

Driver.pm 78 KB

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