Driver.pm 72 KB

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