1
0

Driver.pm 71 KB

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