Driver.pm 69 KB

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