Driver.pm 72 KB

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