1
0

Driver.pm 71 KB

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