1
0

Driver.pm 72 KB

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