Driver.pm 69 KB

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