1
0

Driver.pm 77 KB

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