1
0

Driver.pm 77 KB

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