Driver.pm 72 KB

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