Driver.pm 71 KB

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