1
0

Driver.pm 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  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 Selenium::Remote::MockRemoteConnection;
  18. use Selenium::Remote::MockCommands;
  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 { 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. if ( $self->testing ) {
  257. return Selenium::Remote::MockRemoteConnection->new(
  258. spec => $self->spec,
  259. mock_cmds => $self->commands,
  260. );
  261. }
  262. else {
  263. return Selenium::Remote::RemoteConnection->new(
  264. remote_server_addr => $self->remote_server_addr,
  265. port => $self->port,
  266. ua => $self->ua
  267. );
  268. }
  269. },
  270. );
  271. has 'spec' => (
  272. is => 'ro',
  273. default => sub { {}} ,
  274. );
  275. has 'ua' => (
  276. is => 'lazy',
  277. builder => sub { return LWP::UserAgent->new }
  278. );
  279. has 'commands' => (
  280. is => 'lazy',
  281. builder => sub {
  282. my $self = shift;
  283. if ( $self->testing ) {
  284. return Selenium::Remote::MockCommands->new;
  285. }
  286. else {
  287. return Selenium::Remote::Commands->new;
  288. }
  289. },
  290. );
  291. has 'auto_close' => (
  292. is => 'rw',
  293. coerce => sub { ( defined($_[0]) ? $_[0] : 1 )},
  294. default => sub {1},
  295. );
  296. has 'pid' => (
  297. is => 'lazy',
  298. builder => sub { return $$ }
  299. );
  300. has 'javascript' => (
  301. is => 'rw',
  302. coerce => sub { $_[0] ? JSON::true : JSON::false },
  303. default => sub { return JSON::true }
  304. );
  305. has 'accept_ssl_certs' => (
  306. is => 'rw',
  307. coerce => sub { $_[0] ? JSON::true : JSON::false },
  308. default => sub { return JSON::true }
  309. );
  310. has 'proxy' => (
  311. is => 'rw',
  312. coerce => sub {
  313. my $proxy = $_[0];
  314. if ( $proxy->{proxyType} eq 'pac' ) {
  315. if ( not defined $proxy->{proxyAutoconfigUrl} ) {
  316. croak "proxyAutoconfigUrl not provided\n";
  317. }
  318. elsif ( not( $proxy->{proxyAutoconfigUrl} =~ /^http/g ) ) {
  319. croak "proxyAutoconfigUrl should be of format http://";
  320. }
  321. }
  322. $proxy;
  323. },
  324. );
  325. has 'extra_capabilities' => (
  326. is => 'rw',
  327. default => sub { {} }
  328. );
  329. has 'firefox_profile' => (
  330. is => 'rw',
  331. coerce => sub {
  332. my $profile = shift;
  333. unless (Scalar::Util::blessed($profile)
  334. && $profile->isa('Selenium::Remote::Driver::Firefox::Profile')) {
  335. croak "firefox_profile should be a Selenium::Remote::Driver::Firefox::Profile\n";
  336. }
  337. return $profile->_encode;
  338. },
  339. predicate => 'has_firefox_profile'
  340. );
  341. has 'desired_capabilities' => (
  342. is => 'rw',
  343. lazy => 1,
  344. predicate => 'has_desired_capabilities'
  345. );
  346. has 'inner_window_size' => (
  347. is => 'rw',
  348. lazy => 1,
  349. predicate => 1,
  350. coerce => sub {
  351. my $size = shift;
  352. croak "inner_window_size must have two elements: [ height, width ]"
  353. unless scalar @$size == 2;
  354. foreach my $dim (@$size) {
  355. croak 'inner_window_size only accepts integers, not: ' . $dim
  356. unless Scalar::Util::looks_like_number($dim);
  357. }
  358. return $size;
  359. },
  360. );
  361. has 'testing' => (
  362. is => 'rw',
  363. default => sub { 0 },
  364. );
  365. sub BUILD {
  366. my $self = shift;
  367. if ($self->has_desired_capabilities) {
  368. $self->new_desired_session( $self->desired_capabilities );
  369. }
  370. else {
  371. # Connect to remote server & establish a new session
  372. $self->new_session( $self->extra_capabilities );
  373. }
  374. if ( !( defined $self->session_id ) ) {
  375. croak "Could not establish a session with the remote server\n";
  376. }
  377. elsif ($self->has_inner_window_size) {
  378. my $size = $self->inner_window_size;
  379. $self->set_inner_window_size(@$size);
  380. }
  381. }
  382. sub new_from_caps {
  383. my ($self, %args) = @_;
  384. if (not exists $args{desired_capabilities}) {
  385. $args{desired_capabilities} = {};
  386. }
  387. return $self->new(%args);
  388. }
  389. sub DEMOLISH {
  390. my ($self) = @_;
  391. return if $$ != $self->pid;
  392. $self->quit() if ( $self->auto_close && defined $self->session_id );
  393. }
  394. # This is an internal method used the Driver & is not supposed to be used by
  395. # end user. This method is used by Driver to set up all the parameters
  396. # (url & JSON), send commands & receive processed response from the server.
  397. sub _execute_command {
  398. my ( $self, $res, $params ) = @_;
  399. $res->{'session_id'} = $self->session_id;
  400. $DB::single = 1;
  401. my $resource = $self->commands->get_params($res);
  402. if ($resource) {
  403. $params = {} unless $params;
  404. my $resp = $self->remote_conn->request(
  405. $resource->{method},
  406. $resource->{url},
  407. $resource->{no_content_success},
  408. $params
  409. );
  410. if ( ref($resp) eq 'HASH' ) {
  411. if ( $resp->{cmd_status} && $resp->{cmd_status} eq 'OK' ) {
  412. return $resp->{cmd_return};
  413. }
  414. else {
  415. my $msg = "Error while executing command";
  416. if ( $resp->{cmd_error} ) {
  417. $msg .= ": $resp->{cmd_error}" if $resp->{cmd_error};
  418. }
  419. elsif ( $resp->{cmd_return} ) {
  420. if ( ref( $resp->{cmd_return} ) eq 'HASH' ) {
  421. $msg .= ": $resp->{cmd_return}->{error}->{msg}"
  422. if $resp->{cmd_return}->{error}->{msg};
  423. $msg .= ": $resp->{cmd_return}->{message}"
  424. if $resp->{cmd_return}->{message};
  425. }
  426. else {
  427. $msg .= ": $resp->{cmd_return}";
  428. }
  429. }
  430. croak $msg;
  431. }
  432. }
  433. return $resp;
  434. }
  435. else {
  436. croak "Couldn't retrieve command settings properly\n";
  437. }
  438. }
  439. # A method that is used by the Driver itself. It'll be called to set the
  440. # desired capabilities on the server.
  441. sub new_session {
  442. my ( $self, $extra_capabilities ) = @_;
  443. $extra_capabilities ||= {};
  444. my $args = {
  445. 'desiredCapabilities' => {
  446. 'browserName' => $self->browser_name,
  447. 'platform' => $self->platform,
  448. 'javascriptEnabled' => $self->javascript,
  449. 'version' => $self->version,
  450. 'acceptSslCerts' => $self->accept_ssl_certs,
  451. %$extra_capabilities,
  452. },
  453. };
  454. if ( defined $self->proxy ) {
  455. $args->{desiredCapabilities}->{proxy} = $self->proxy;
  456. }
  457. if ($args->{desiredCapabilities}->{browserName} =~ /firefox/i
  458. && $self->has_firefox_profile) {
  459. $args->{desiredCapabilities}->{firefox_profile} = $self->firefox_profile;
  460. }
  461. $self->_request_new_session($args);
  462. }
  463. sub new_desired_session {
  464. my ( $self, $caps ) = @_;
  465. $self->_request_new_session({
  466. desiredCapabilities => $caps
  467. });
  468. }
  469. sub _request_new_session {
  470. my ( $self, $args ) = @_;
  471. # command => 'newSession' to fool the tests of commands implemented
  472. # TODO: rewrite the testing better, this is so fragile.
  473. my $resp = $self->remote_conn->request(
  474. $self->commands->get_method('newSession'),
  475. $self->commands->get_url('newSession'),
  476. $self->commands->get_no_content_success('newSession'),
  477. $args,
  478. );
  479. if ( ( defined $resp->{'sessionId'} ) && $resp->{'sessionId'} ne '' ) {
  480. $self->session_id( $resp->{'sessionId'} );
  481. }
  482. else {
  483. my $error = 'Could not create new session';
  484. $error .= ': ' . $resp->{cmd_return}->{message}
  485. if exists $resp->{cmd_return}->{message};
  486. croak $error;
  487. }
  488. }
  489. =head2 debug_on
  490. Description:
  491. Turns on debugging mode and the driver will print extra info like request
  492. and response to stdout. Useful, when you want to see what is being sent to
  493. the server & what response you are getting back.
  494. Usage:
  495. $driver->debug_on;
  496. =cut
  497. sub debug_on {
  498. my ($self) = @_;
  499. $self->remote_conn->debug(1);
  500. }
  501. =head2 debug_off
  502. Description:
  503. Turns off the debugging mode.
  504. Usage:
  505. $driver->debug_off;
  506. =cut
  507. sub debug_off {
  508. my ($self) = @_;
  509. $self->remote_conn->debug(0);
  510. }
  511. =head2 get_sessions
  512. Description:
  513. Returns a list of the currently active sessions. Each session will be
  514. returned as an array of Hashes with the following keys:
  515. 'id' : The session ID
  516. 'capabilities: An object describing session's capabilities
  517. Output:
  518. Array of Hashes
  519. Usage:
  520. print Dumper $driver->get_sessions();
  521. =cut
  522. sub get_sessions {
  523. my ($self) = @_;
  524. my $res = { 'command' => 'getSessions' };
  525. return $self->_execute_command($res);
  526. }
  527. =head2 status
  528. Description:
  529. Query the server's current status. All server implementations
  530. should return two basic objects describing the server's current
  531. platform and when the server was built.
  532. Output:
  533. Hash ref
  534. Usage:
  535. print Dumper $driver->status;
  536. =cut
  537. sub status {
  538. my ($self) = @_;
  539. my $res = { 'command' => 'status' };
  540. return $self->_execute_command($res);
  541. }
  542. =head2 get_alert_text
  543. Description:
  544. Gets the text of the currently displayed JavaScript alert(), confirm()
  545. or prompt() dialog.
  546. Example
  547. my $string = $driver->get_alert_text;
  548. =cut
  549. sub get_alert_text {
  550. my ($self) = @_;
  551. my $res = { 'command' => 'getAlertText' };
  552. return $self->_execute_command($res);
  553. }
  554. =head2 send_keys_to_active_element
  555. Description:
  556. Send a sequence of key strokes to the active element. This command is
  557. similar to the send keys command in every aspect except the implicit
  558. termination: The modifiers are not released at the end of the call.
  559. Rather, the state of the modifier keys is kept between calls, so mouse
  560. interactions can be performed while modifier keys are depressed.
  561. Input: 1
  562. Required:
  563. {ARRAY | STRING} - Array of strings or a string.
  564. Usage:
  565. $driver->send_keys_to_active_element('abcd', 'efg');
  566. $driver->send_keys_to_active_element('hijk');
  567. or
  568. # include the WDKeys module
  569. use Selenium::Remote::WDKeys;
  570. .
  571. .
  572. $driver->send_keys_to_active_element(KEYS->{'space'}, KEYS->{'enter'});
  573. =cut
  574. sub send_keys_to_active_element {
  575. my ( $self, @strings ) = @_;
  576. my $res = { 'command' => 'sendKeysToActiveElement' };
  577. my $params = {
  578. 'value' => \@strings,
  579. };
  580. return $self->_execute_command( $res, $params );
  581. }
  582. =head2 send_keys_to_alert
  583. Synonymous with send_keys_to_prompt
  584. =cut
  585. sub send_keys_to_alert {
  586. return shift->send_keys_to_prompt(@_);
  587. }
  588. =head2 send_keys_to_prompt
  589. Description:
  590. Sends keystrokes to a JavaScript prompt() dialog.
  591. Input:
  592. {string} keys to send
  593. Example:
  594. $driver->send_keys_to_prompt('hello world');
  595. or
  596. ok($driver->get_alert_text eq 'Please Input your name','prompt appears');
  597. $driver->send_keys_to_alert("Larry Wall");
  598. $driver->accept_alert;
  599. =cut
  600. sub send_keys_to_prompt {
  601. my ( $self, $keys ) = @_;
  602. my $res = { 'command' => 'sendKeysToPrompt' };
  603. my $params = { 'text' => $keys };
  604. return $self->_execute_command( $res, $params );
  605. }
  606. =head2 accept_alert
  607. Description:
  608. Accepts the currently displayed alert dialog. Usually, this is
  609. equivalent to clicking the 'OK' button in the dialog.
  610. Example:
  611. $driver->accept_alert;
  612. =cut
  613. sub accept_alert {
  614. my ($self) = @_;
  615. my $res = { 'command' => 'acceptAlert' };
  616. return $self->_execute_command($res);
  617. }
  618. =head2 dismiss_alert
  619. Description:
  620. Dismisses the currently displayed alert dialog. For comfirm()
  621. and prompt() dialogs, this is equivalent to clicking the
  622. 'Cancel' button. For alert() dialogs, this is equivalent to
  623. clicking the 'OK' button.
  624. Example:
  625. $driver->dismiss_alert;
  626. =cut
  627. sub dismiss_alert {
  628. my ($self) = @_;
  629. my $res = { 'command' => 'dismissAlert' };
  630. return $self->_execute_command($res);
  631. }
  632. =head2 mouse_move_to_location
  633. Description:
  634. Move the mouse by an offset of the specificed element. If no
  635. element is specified, the move is relative to the current mouse
  636. cursor. If an element is provided but no offset, the mouse will be
  637. moved to the center of the element. If the element is not visible,
  638. it will be scrolled into view.
  639. Output:
  640. STRING -
  641. Usage:
  642. # element - the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
  643. # 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.
  644. # 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.
  645. print $driver->mouse_move_to_location(element => e, xoffset => x, yoffset => y);
  646. =cut
  647. sub mouse_move_to_location {
  648. my ( $self, %params ) = @_;
  649. $params{element} = $params{element}{id} if exists $params{element};
  650. my $res = { 'command' => 'mouseMoveToLocation' };
  651. return $self->_execute_command( $res, \%params );
  652. }
  653. =head2 move_to
  654. Synonymous with mouse_move_to_location
  655. =cut
  656. sub move_to {
  657. return shift->mouse_move_to_location(@_);
  658. }
  659. =head2 get_capabilities
  660. Description:
  661. Retrieve the capabilities of the specified session.
  662. Output:
  663. HASH of all the capabilities.
  664. Usage:
  665. my $capab = $driver->get_capabilities();
  666. print Dumper($capab);
  667. =cut
  668. sub get_capabilities {
  669. my $self = shift;
  670. my $res = { 'command' => 'getCapabilities' };
  671. return $self->_execute_command($res);
  672. }
  673. =head2 set_timeout
  674. Description:
  675. Configure the amount of time that a particular type of operation can execute
  676. for before they are aborted and a |Timeout| error is returned to the client.
  677. Input:
  678. type - <STRING> - The type of operation to set the timeout for.
  679. Valid values are:
  680. "script" : for script timeouts,
  681. "implicit" : for modifying the implicit wait timeout
  682. "page load" : for setting a page load timeout.
  683. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  684. commands are permitted to run.
  685. Usage:
  686. $driver->set_timeout('script', 1000);
  687. =cut
  688. sub set_timeout {
  689. my ( $self, $type, $ms ) = @_;
  690. if ( not defined $type or not defined $ms ) {
  691. croak "Expecting type & timeout in ms";
  692. }
  693. my $res = { 'command' => 'setTimeout' };
  694. my $params = { 'type' => $type, 'ms' => $ms };
  695. return $self->_execute_command( $res, $params );
  696. }
  697. =head2 set_async_script_timeout
  698. Description:
  699. Set the amount of time, in milliseconds, that asynchronous scripts executed
  700. by execute_async_script() are permitted to run before they are
  701. aborted and a |Timeout| error is returned to the client.
  702. Input:
  703. ms - <NUMBER> - The amount of time, in milliseconds, that time-limited
  704. commands are permitted to run.
  705. Usage:
  706. $driver->set_async_script_timeout(1000);
  707. =cut
  708. sub set_async_script_timeout {
  709. my ( $self, $ms ) = @_;
  710. if ( not defined $ms ) {
  711. croak "Expecting timeout in ms";
  712. }
  713. my $res = { 'command' => 'setAsyncScriptTimeout' };
  714. my $params = { 'ms' => $ms };
  715. return $self->_execute_command( $res, $params );
  716. }
  717. =head2 set_implicit_wait_timeout
  718. Description:
  719. Set the amount of time the driver should wait when searching for elements.
  720. When searching for a single element, the driver will poll the page until
  721. an element is found or the timeout expires, whichever occurs first.
  722. When searching for multiple elements, the driver should poll the page until
  723. at least one element is found or the timeout expires, at which point it
  724. will return an empty list. If this method is never called, the driver will
  725. default to an implicit wait of 0ms.
  726. Input:
  727. Time in milliseconds.
  728. Output:
  729. Server Response Hash with no data returned back from the server.
  730. Usage:
  731. $driver->set_implicit_wait_timeout(10);
  732. =cut
  733. sub set_implicit_wait_timeout {
  734. my ( $self, $ms ) = @_;
  735. my $res = { 'command' => 'setImplicitWaitTimeout' };
  736. my $params = { 'ms' => $ms };
  737. return $self->_execute_command( $res, $params );
  738. }
  739. =head2 pause
  740. Description:
  741. Pause execution for a specified interval of milliseconds.
  742. Usage:
  743. $driver->pause(10000); # 10 second delay
  744. $driver->pause(); # 1 second delay default
  745. =cut
  746. sub pause {
  747. my $self = shift;
  748. my $timeout = ( shift // 1000 ) / 1000;
  749. select( undef, undef, undef, $timeout ); # Fractional-second sleep
  750. }
  751. =head2 close
  752. Description:
  753. Close the current window.
  754. Usage:
  755. $driver->close();
  756. or
  757. #close a popup window
  758. my $handles = $driver->get_window_handles;
  759. $driver->switch_to_window($handles->[1]);
  760. $driver->close();
  761. $driver->switch_to_window($handles->[0]);
  762. =cut
  763. sub close {
  764. my $self = shift;
  765. my $res = { 'command' => 'close' };
  766. $self->_execute_command($res);
  767. }
  768. =head2 quit
  769. Description:
  770. Delete the session & close open browsers.
  771. Usage:
  772. $driver->quit();
  773. =cut
  774. sub quit {
  775. my $self = shift;
  776. my $res = { 'command' => 'quit' };
  777. $self->_execute_command($res);
  778. $self->session_id(undef);
  779. }
  780. =head2 get_current_window_handle
  781. Description:
  782. Retrieve the current window handle.
  783. Output:
  784. STRING - the window handle
  785. Usage:
  786. print $driver->get_current_window_handle();
  787. =cut
  788. sub get_current_window_handle {
  789. my $self = shift;
  790. my $res = { 'command' => 'getCurrentWindowHandle' };
  791. return $self->_execute_command($res);
  792. }
  793. =head2 get_window_handles
  794. Description:
  795. Retrieve the list of window handles used in the session.
  796. Output:
  797. ARRAY of STRING - list of the window handles
  798. Usage:
  799. print Dumper $driver->get_window_handles;
  800. or
  801. # get popup, close, then back
  802. my $handles = $driver->get_window_handles;
  803. $driver->switch_to_window($handles->[1]);
  804. $driver->close;
  805. $driver->switch_to_window($handles->[0]);
  806. =cut
  807. sub get_window_handles {
  808. my $self = shift;
  809. my $res = { 'command' => 'getWindowHandles' };
  810. return $self->_execute_command($res);
  811. }
  812. =head2 get_window_size
  813. Description:
  814. Retrieve the window size
  815. Input:
  816. STRING - <optional> - window handle (default is 'current' window)
  817. Output:
  818. HASH - containing keys 'height' & 'width'
  819. Usage:
  820. my $window_size = $driver->get_window_size();
  821. print $window_size->{'height'}, $window_size->('width');
  822. =cut
  823. sub get_window_size {
  824. my ( $self, $window ) = @_;
  825. $window = ( defined $window ) ? $window : 'current';
  826. my $res = { 'command' => 'getWindowSize', 'window_handle' => $window };
  827. return $self->_execute_command($res);
  828. }
  829. =head2 get_window_position
  830. Description:
  831. Retrieve the window position
  832. Input:
  833. STRING - <optional> - window handle (default is 'current' window)
  834. Output:
  835. HASH - containing keys 'x' & 'y'
  836. Usage:
  837. my $window_size = $driver->get_window_position();
  838. print $window_size->{'x'}, $window_size->('y');
  839. =cut
  840. sub get_window_position {
  841. my ( $self, $window ) = @_;
  842. $window = ( defined $window ) ? $window : 'current';
  843. my $res = { 'command' => 'getWindowPosition', 'window_handle' => $window };
  844. return $self->_execute_command($res);
  845. }
  846. =head2 get_current_url
  847. Description:
  848. Retrieve the url of the current page
  849. Output:
  850. STRING - url
  851. Usage:
  852. print $driver->get_current_url();
  853. =cut
  854. sub get_current_url {
  855. my $self = shift;
  856. my $res = { 'command' => 'getCurrentUrl' };
  857. return $self->_execute_command($res);
  858. }
  859. =head2 navigate
  860. Description:
  861. Navigate to a given url. This is same as get() method.
  862. Input:
  863. STRING - url
  864. Usage:
  865. $driver->navigate('http://www.google.com');
  866. =cut
  867. sub navigate {
  868. my ( $self, $url ) = @_;
  869. $self->get($url);
  870. }
  871. =head2 get
  872. Description:
  873. Navigate to a given url
  874. Input:
  875. STRING - url
  876. Usage:
  877. $driver->get('http://www.google.com');
  878. =cut
  879. sub get {
  880. my ( $self, $url ) = @_;
  881. if ($self->has_base_url && $url !~ m|://|) {
  882. $url =~ s|^/||;
  883. $url = $self->base_url . "/" . $url;
  884. }
  885. my $res = { 'command' => 'get' };
  886. my $params = { 'url' => $url };
  887. return $self->_execute_command( $res, $params );
  888. }
  889. =head2 get_title
  890. Description:
  891. Get the current page title
  892. Output:
  893. STRING - Page title
  894. Usage:
  895. print $driver->get_title();
  896. =cut
  897. sub get_title {
  898. my $self = shift;
  899. my $res = { 'command' => 'getTitle' };
  900. return $self->_execute_command($res);
  901. }
  902. =head2 go_back
  903. Description:
  904. Equivalent to hitting the back button on the browser.
  905. Usage:
  906. $driver->go_back();
  907. =cut
  908. sub go_back {
  909. my $self = shift;
  910. my $res = { 'command' => 'goBack' };
  911. return $self->_execute_command($res);
  912. }
  913. =head2 go_forward
  914. Description:
  915. Equivalent to hitting the forward button on the browser.
  916. Usage:
  917. $driver->go_forward();
  918. =cut
  919. sub go_forward {
  920. my $self = shift;
  921. my $res = { 'command' => 'goForward' };
  922. return $self->_execute_command($res);
  923. }
  924. =head2 refresh
  925. Description:
  926. Reload the current page.
  927. Usage:
  928. $driver->refresh();
  929. =cut
  930. sub refresh {
  931. my $self = shift;
  932. my $res = { 'command' => 'refresh' };
  933. return $self->_execute_command($res);
  934. }
  935. =head2 javascript
  936. Description:
  937. returns true if javascript is enabled in the driver.
  938. Usage:
  939. if ($driver->has_javascript) { ...; }
  940. =cut
  941. sub has_javascript {
  942. my $self = shift;
  943. return int($self->javascript);
  944. }
  945. =head2 execute_async_script
  946. Description:
  947. Inject a snippet of JavaScript into the page for execution in the context
  948. of the currently selected frame. The executed script is assumed to be
  949. asynchronous and must signal that is done by invoking the provided
  950. callback, which is always provided as the final argument to the function.
  951. The value to this callback will be returned to the client.
  952. Asynchronous script commands may not span page loads. If an unload event
  953. is fired while waiting for a script result, an error should be returned
  954. to the client.
  955. Input: 2 (1 optional)
  956. Required:
  957. STRING - Javascript to execute on the page
  958. Optional:
  959. ARRAY - list of arguments that need to be passed to the script.
  960. Output:
  961. {*} - Varied, depending on the type of result expected back from the script.
  962. Usage:
  963. my $script = q{
  964. var arg1 = arguments[0];
  965. var callback = arguments[arguments.length-1];
  966. var elem = window.document.findElementById(arg1);
  967. callback(elem);
  968. };
  969. my $elem = $driver->execute_async_script($script,'myid');
  970. $elem->click;
  971. =cut
  972. sub execute_async_script {
  973. my ( $self, $script, @args ) = @_;
  974. if ( $self->has_javascript ) {
  975. if ( not defined $script ) {
  976. croak 'No script provided';
  977. }
  978. my $res = { 'command' => 'executeAsyncScript' };
  979. # Check the args array if the elem obj is provided & replace it with
  980. # JSON representation
  981. for ( my $i = 0; $i < @args; $i++ ) {
  982. if ( Scalar::Util::blessed( $args[$i] )
  983. and $args[$i]->isa('Selenium::Remote::WebElement') )
  984. {
  985. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  986. }
  987. }
  988. my $params = { 'script' => $script, 'args' => \@args };
  989. my $ret = $self->_execute_command( $res, $params );
  990. # replace any ELEMENTS with WebElement
  991. if ( ref($ret)
  992. and ( ref($ret) eq 'HASH' )
  993. and exists $ret->{'ELEMENT'} )
  994. {
  995. $ret = $self->webelement_class->new( id => $ret->{ELEMENT},
  996. driver => $self );
  997. }
  998. return $ret;
  999. }
  1000. else {
  1001. croak 'Javascript is not enabled on remote driver instance.';
  1002. }
  1003. }
  1004. =head2 execute_script
  1005. Description:
  1006. Inject a snippet of JavaScript into the page and return its result.
  1007. WebElements that should be passed to the script as an argument should be
  1008. specified in the arguments array as WebElement object. Likewise,
  1009. any WebElements in the script result will be returned as WebElement object.
  1010. Input: 2 (1 optional)
  1011. Required:
  1012. STRING - Javascript to execute on the page
  1013. Optional:
  1014. ARRAY - list of arguments that need to be passed to the script.
  1015. Output:
  1016. {*} - Varied, depending on the type of result expected back from the script.
  1017. Usage:
  1018. my $script = q{
  1019. var arg1 = arguments[0];
  1020. var elem = window.document.findElementById(arg1);
  1021. return elem;
  1022. };
  1023. my $elem = $driver->execute_script($script,'myid');
  1024. $elem->click;
  1025. =cut
  1026. sub execute_script {
  1027. my ( $self, $script, @args ) = @_;
  1028. if ( $self->has_javascript ) {
  1029. if ( not defined $script ) {
  1030. croak 'No script provided';
  1031. }
  1032. my $res = { 'command' => 'executeScript' };
  1033. # Check the args array if the elem obj is provided & replace it with
  1034. # JSON representation
  1035. for ( my $i = 0; $i < @args; $i++ ) {
  1036. if ( Scalar::Util::blessed( $args[$i] )
  1037. and $args[$i]->isa('Selenium::Remote::WebElement') )
  1038. {
  1039. $args[$i] = { 'ELEMENT' => ( $args[$i] )->{id} };
  1040. }
  1041. }
  1042. my $params = { 'script' => $script, 'args' => [@args] };
  1043. my $ret = $self->_execute_command( $res, $params );
  1044. return $self->_convert_to_webelement($ret);
  1045. }
  1046. else {
  1047. croak 'Javascript is not enabled on remote driver instance.';
  1048. }
  1049. }
  1050. # _convert_to_webelement
  1051. # An internal method used to traverse a data structure
  1052. # and convert any ELEMENTS with WebElements
  1053. sub _convert_to_webelement {
  1054. my ( $self, $ret ) = @_;
  1055. if ( ref($ret) and ( ref($ret) eq 'HASH' ) ) {
  1056. if ( ( keys %$ret == 1 ) and exists $ret->{'ELEMENT'} ) {
  1057. # replace an ELEMENT with WebElement
  1058. return $self->webelement_class->new( id => $ret->{ELEMENT},
  1059. driver => $self );
  1060. }
  1061. my %hash;
  1062. foreach my $key ( keys %$ret ) {
  1063. $hash{$key} = $self->_convert_to_webelement( $ret->{$key} );
  1064. }
  1065. return \%hash;
  1066. }
  1067. if ( ref($ret) and ( ref($ret) eq 'ARRAY' ) ) {
  1068. my @array = map { $self->_convert_to_webelement($_) } @$ret;
  1069. return \@array;
  1070. }
  1071. return $ret;
  1072. }
  1073. =head2 screenshot
  1074. Description:
  1075. Get a screenshot of the current page as a base64 encoded image.
  1076. Output:
  1077. STRING - base64 encoded image
  1078. Usage:
  1079. print $driver->screenshot();
  1080. To conveniently write the screenshot to a file, see L<capture_screenshot()>.
  1081. =cut
  1082. sub screenshot {
  1083. my ($self) = @_;
  1084. my $res = { 'command' => 'screenshot' };
  1085. return $self->_execute_command($res);
  1086. }
  1087. =head2 capture_screenshot
  1088. Description:
  1089. Capture a screenshot and save as a PNG to provided file name.
  1090. (The method is compatible with the WWW::Selenium method fo the same name)
  1091. Output:
  1092. TRUE - (Screenshot is written to file)
  1093. Usage:
  1094. $driver->capture_screenshot($filename);
  1095. =cut
  1096. sub capture_screenshot {
  1097. my ( $self, $filename ) = @_;
  1098. croak '$filename is required' unless $filename;
  1099. require MIME::Base64;
  1100. open( my $fh, '>', $filename );
  1101. binmode $fh;
  1102. print $fh MIME::Base64::decode_base64( $self->screenshot() );
  1103. CORE::close $fh;
  1104. return 1;
  1105. }
  1106. =head2 available_engines
  1107. Description:
  1108. List all available engines on the machine. To use an engine, it has to be present in this list.
  1109. Output:
  1110. {Array.<string>} A list of available engines
  1111. Usage:
  1112. print Dumper $driver->available_engines;
  1113. =cut
  1114. sub available_engines {
  1115. my ($self) = @_;
  1116. my $res = { 'command' => 'availableEngines' };
  1117. return $self->_execute_command($res);
  1118. }
  1119. =head2 switch_to_frame
  1120. Description:
  1121. Change focus to another frame on the page. If the frame ID is null, the
  1122. server will switch to the page's default content. You can also switch to a
  1123. WebElement, for e.g. you can find an iframe using find_element & then
  1124. provide that as an input to this method. Also see e.g.
  1125. Input: 1
  1126. Required:
  1127. {STRING | NUMBER | NULL | WebElement} - ID of the frame which can be one of the three
  1128. mentioned.
  1129. Usage:
  1130. $driver->switch_to_frame('frame_1');
  1131. or
  1132. $driver->switch_to_frame($driver->find_element('iframe', 'tag_name'));
  1133. =cut
  1134. sub switch_to_frame {
  1135. my ( $self, $id ) = @_;
  1136. my $json_null = JSON::null;
  1137. my $params;
  1138. $id = ( defined $id ) ? $id : $json_null;
  1139. my $res = { 'command' => 'switchToFrame' };
  1140. if ( ref $id eq $self->webelement_class ) {
  1141. $params = { 'id' => { 'ELEMENT' => $id->{'id'} } };
  1142. }
  1143. else {
  1144. $params = { 'id' => $id };
  1145. }
  1146. return $self->_execute_command( $res, $params );
  1147. }
  1148. =head2 switch_to_window
  1149. Description:
  1150. Change focus to another window. The window to change focus to may
  1151. be specified by its server assigned window handle, or by the value
  1152. of the page's window.name attribute.
  1153. If you wish to use the window name as the target, you'll need to
  1154. have set C<window.name> on the page either in app code or via
  1155. L</execute_script>, or pass a name as the second argument to the
  1156. C<window.open()> function when opening the new window. Note that
  1157. the window name used here has nothing to do with the window title,
  1158. or the C<< <title> >> element on the page.
  1159. Otherwise, use L</get_window_handles> and select a
  1160. Webdriver-generated handle from the output of that function.
  1161. Input: 1
  1162. Required:
  1163. STRING - Window handle or the Window name
  1164. Usage:
  1165. $driver->switch_to_window('MY Homepage');
  1166. or
  1167. # close a popup window and switch back
  1168. my $handles = $driver->get_window_handles;
  1169. $driver->switch_to_window($handles->[1]);
  1170. $driver->close;
  1171. $driver->switch_to_window($handles->[0]);
  1172. =cut
  1173. sub switch_to_window {
  1174. my ( $self, $name ) = @_;
  1175. if ( not defined $name ) {
  1176. return 'Window name not provided';
  1177. }
  1178. my $res = { 'command' => 'switchToWindow' };
  1179. my $params = { 'name' => $name };
  1180. return $self->_execute_command( $res, $params );
  1181. }
  1182. =head2 get_speed
  1183. Description:
  1184. Get the current user input speed. The actual input speed is still browser
  1185. specific and not covered by the Driver.
  1186. Output:
  1187. STRING - One of these: SLOW, MEDIUM, FAST
  1188. Usage:
  1189. print $driver->get_speed();
  1190. =cut
  1191. sub get_speed {
  1192. my ($self) = @_;
  1193. my $res = { 'command' => 'getSpeed' };
  1194. return $self->_execute_command($res);
  1195. }
  1196. =head2 set_speed
  1197. Description:
  1198. Set the user input speed.
  1199. Input:
  1200. STRING - One of these: SLOW, MEDIUM, FAST
  1201. Usage:
  1202. $driver->set_speed('MEDIUM');
  1203. Note: This function is a no-op in WebDriver (?). See
  1204. https://groups.google.com/d/topic/selenium-users/oX0ZnYFPuSA/discussion and
  1205. http://code.google.com/p/selenium/source/browse/trunk/java/client/src/org/openqa/selenium/WebDriverCommandProcessor.java
  1206. =cut
  1207. sub set_speed {
  1208. my ( $self, $speed ) = @_;
  1209. if ( not defined $speed ) {
  1210. return 'Speed not provided.';
  1211. }
  1212. my $res = { 'command' => 'setSpeed' };
  1213. my $params = { 'speed' => $speed };
  1214. return $self->_execute_command( $res, $params );
  1215. }
  1216. =head2 set_window_position
  1217. Description:
  1218. Set the position (on screen) where you want your browser to be displayed.
  1219. Input:
  1220. INT - x co-ordinate
  1221. INT - y co-ordinate
  1222. STRING - <optional> - window handle (default is 'current' window)
  1223. Output:
  1224. BOOLEAN - Success or failure
  1225. Usage:
  1226. $driver->set_window_position(50, 50);
  1227. =cut
  1228. sub set_window_position {
  1229. my ( $self, $x, $y, $window ) = @_;
  1230. $window = ( defined $window ) ? $window : 'current';
  1231. if ( not defined $x and not defined $y ) {
  1232. croak "X & Y co-ordinates are required";
  1233. }
  1234. my $res = { 'command' => 'setWindowPosition', 'window_handle' => $window };
  1235. my $params = { 'x' => $x, 'y' => $y };
  1236. my $ret = $self->_execute_command( $res, $params );
  1237. return $ret ? 1 : 0;
  1238. }
  1239. =head2 set_window_size
  1240. Description:
  1241. Set the size of the browser window
  1242. Input:
  1243. INT - height of the window
  1244. INT - width of the window
  1245. STRING - <optional> - window handle (default is 'current' window)
  1246. Output:
  1247. BOOLEAN - Success or failure
  1248. Usage:
  1249. $driver->set_window_size(640, 480);
  1250. =cut
  1251. sub set_window_size {
  1252. my ( $self, $height, $width, $window ) = @_;
  1253. $window = ( defined $window ) ? $window : 'current';
  1254. if ( not defined $height and not defined $width ) {
  1255. croak "height & width of browser are required";
  1256. }
  1257. my $res = { 'command' => 'setWindowSize', 'window_handle' => $window };
  1258. my $params = { 'height' => $height, 'width' => $width };
  1259. my $ret = $self->_execute_command( $res, $params );
  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 ) ? 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 - class, class_name, css, id, link,
  1410. link_text, partial_link_text, name, tag_name, xpath";
  1411. }
  1412. }
  1413. =head2 find_elements
  1414. Description:
  1415. Search for multiple elements on the page, starting from the document root.
  1416. The located elements will be returned as an array of WebElement object.
  1417. Input: 2 (1 optional)
  1418. Required:
  1419. STRING - The search target.
  1420. Optional:
  1421. STRING - Locator scheme to use to search the element, available schemes:
  1422. {class, class_name, css, id, link, link_text, partial_link_text,
  1423. tag_name, name, xpath}
  1424. Defaults to 'xpath' if not configured global during instantiation.
  1425. Output:
  1426. ARRAY or ARRAYREF of WebElement Objects
  1427. Usage:
  1428. $driver->find_elements("//input");
  1429. =cut
  1430. sub find_elements {
  1431. my ( $self, $query, $method ) = @_;
  1432. if ( not defined $query ) {
  1433. croak 'Search string to find element not provided.';
  1434. }
  1435. my $using =
  1436. ( defined $method ) ? FINDERS->{$method} : $self->default_finder;
  1437. if ( defined $using ) {
  1438. my $res = { 'command' => 'findElements' };
  1439. my $params = { 'using' => $using, 'value' => $query };
  1440. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1441. if ($@) {
  1442. if ( $@
  1443. =~ /(An element could not be located on the page using the given search parameters)/
  1444. )
  1445. {
  1446. # give details on what element wasn't found
  1447. $@ = "$1: $query,$using";
  1448. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1449. croak $@;
  1450. }
  1451. else {
  1452. # re throw if the exception wasn't what we expected
  1453. die $@;
  1454. }
  1455. }
  1456. my $elem_obj_arr = [];
  1457. foreach (@$ret_data) {
  1458. push(
  1459. @$elem_obj_arr,
  1460. $self->webelement_class->new(
  1461. id => $_->{ELEMENT}, driver => $self
  1462. )
  1463. );
  1464. }
  1465. return wantarray? @{$elem_obj_arr} : $elem_obj_arr ;
  1466. }
  1467. else {
  1468. croak "Bad method, expected - class, class_name, css, id, link,
  1469. link_text, partial_link_text, name, tag_name, xpath";
  1470. }
  1471. }
  1472. =head2 find_child_element
  1473. Description:
  1474. Search for an element on the page, starting from the identified element. The
  1475. located element will be returned as a WebElement object.
  1476. Input: 3 (1 optional)
  1477. Required:
  1478. Selenium::Remote::WebElement - WebElement object from where you want to
  1479. start searching.
  1480. STRING - The search target. (Do not use a double whack('//')
  1481. in an xpath to search for a child element
  1482. ex: '//option[@id="something"]'
  1483. instead use a dot whack ('./')
  1484. ex: './option[@id="something"]')
  1485. Optional:
  1486. STRING - Locator scheme to use to search the element, available schemes:
  1487. {class, class_name, css, id, link, link_text, partial_link_text,
  1488. tag_name, name, xpath}
  1489. Defaults to 'xpath' if not configured global during instantiation.
  1490. Output:
  1491. WebElement Object
  1492. Usage:
  1493. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1494. # note the usage of ./ when searching for a child element instead of //
  1495. my $child = $driver->find_child_element($elem1, "./option[\@value='es_ar']");
  1496. =cut
  1497. sub find_child_element {
  1498. my ( $self, $elem, $query, $method ) = @_;
  1499. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1500. croak "Missing parameters";
  1501. }
  1502. my $using = ( defined $method ) ? $method : $self->default_finder;
  1503. if ( exists FINDERS->{$using} ) {
  1504. my $res = { 'command' => 'findChildElement', 'id' => $elem->{id} };
  1505. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1506. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1507. if ($@) {
  1508. if ( $@
  1509. =~ /(An element could not be located on the page using the given search parameters)/
  1510. )
  1511. {
  1512. # give details on what element wasn't found
  1513. $@ = "$1: $query,$using";
  1514. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1515. croak $@;
  1516. }
  1517. else {
  1518. # re throw if the exception wasn't what we expected
  1519. die $@;
  1520. }
  1521. }
  1522. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1523. driver => $self );
  1524. }
  1525. else {
  1526. croak "Bad method, expected - class, class_name, css, id, link,
  1527. link_text, partial_link_text, name, tag_name, xpath";
  1528. }
  1529. }
  1530. =head2 find_child_elements
  1531. Description:
  1532. Search for multiple element on the page, starting from the identified
  1533. element. The located elements will be returned as an array of WebElement
  1534. objects.
  1535. Input: 3 (1 optional)
  1536. Required:
  1537. Selenium::Remote::WebElement - WebElement object from where you want to
  1538. start searching.
  1539. STRING - The search target.
  1540. Optional:
  1541. STRING - Locator scheme to use to search the element, available schemes:
  1542. {class, class_name, css, id, link, link_text, partial_link_text,
  1543. tag_name, name, xpath}
  1544. Defaults to 'xpath' if not configured global during instantiation.
  1545. Output:
  1546. ARRAY of WebElement Objects.
  1547. Usage:
  1548. my $elem1 = $driver->find_element("//select[\@name='ned']");
  1549. my $child = $driver->find_child_elements($elem1, "//option");
  1550. =cut
  1551. sub find_child_elements {
  1552. my ( $self, $elem, $query, $method ) = @_;
  1553. if ( ( not defined $elem ) || ( not defined $query ) ) {
  1554. croak "Missing parameters";
  1555. }
  1556. my $using = ( defined $method ) ? $method : $self->default_finder;
  1557. if ( exists FINDERS->{$using} ) {
  1558. my $res = { 'command' => 'findChildElements', 'id' => $elem->{id} };
  1559. my $params = { 'using' => FINDERS->{$using}, 'value' => $query };
  1560. my $ret_data = eval { $self->_execute_command( $res, $params ); };
  1561. if ($@) {
  1562. if ( $@
  1563. =~ /(An element could not be located on the page using the given search parameters)/
  1564. )
  1565. {
  1566. # give details on what element wasn't found
  1567. $@ = "$1: $query,$using";
  1568. local @CARP_NOT = ( "Selenium::Remote::Driver", @CARP_NOT );
  1569. croak $@;
  1570. }
  1571. else {
  1572. # re throw if the exception wasn't what we expected
  1573. die $@;
  1574. }
  1575. }
  1576. my $elem_obj_arr = [];
  1577. my $i = 0;
  1578. foreach (@$ret_data) {
  1579. $elem_obj_arr->[$i] =
  1580. $self->webelement_class->new( id => $_->{ELEMENT},
  1581. driver => $self );
  1582. $i++;
  1583. }
  1584. return wantarray ? @{$elem_obj_arr} : $elem_obj_arr;
  1585. }
  1586. else {
  1587. croak "Bad method, expected - class, class_name, css, id, link,
  1588. link_text, partial_link_text, name, tag_name, xpath";
  1589. }
  1590. }
  1591. =head2 get_active_element
  1592. Description:
  1593. Get the element on the page that currently has focus.. The located element
  1594. will be returned as a WebElement object.
  1595. Output:
  1596. WebElement Object
  1597. Usage:
  1598. $driver->get_active_element();
  1599. =cut
  1600. sub get_active_element {
  1601. my ($self) = @_;
  1602. my $res = { 'command' => 'getActiveElement' };
  1603. my $ret_data = eval { $self->_execute_command($res) };
  1604. if ($@) {
  1605. croak $@;
  1606. }
  1607. else {
  1608. return $self->webelement_class->new( id => $ret_data->{ELEMENT},
  1609. driver => $self );
  1610. }
  1611. }
  1612. =head2 send_modifier
  1613. Description:
  1614. Send an event to the active element to depress or release a modifier key.
  1615. Input: 2
  1616. Required:
  1617. 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
  1618. isdown - Boolean/String - Whether to generate a key down or key up
  1619. Usage:
  1620. $driver->send_modifier('Alt','down');
  1621. $elem->send_keys('c');
  1622. $driver->send_modifier('Alt','up');
  1623. or
  1624. $driver->send_modifier('Alt',1);
  1625. $elem->send_keys('c');
  1626. $driver->send_modifier('Alt',0);
  1627. =cut
  1628. sub send_modifier {
  1629. my ( $self, $modifier, $isdown ) = @_;
  1630. if ( $isdown =~ /(down|up)/ ) {
  1631. $isdown = $isdown =~ /down/ ? 1 : 0;
  1632. }
  1633. my $res = { 'command' => 'sendModifier' };
  1634. my $params = {
  1635. value => $modifier,
  1636. isdown => $isdown
  1637. };
  1638. return $self->_execute_command( $res, $params );
  1639. }
  1640. =head2 compare_elements
  1641. Description:
  1642. Test if two element IDs refer to the same DOM element.
  1643. Input: 2
  1644. Required:
  1645. Selenium::Remote::WebElement - WebElement Object
  1646. Selenium::Remote::WebElement - WebElement Object
  1647. Output:
  1648. BOOLEAN
  1649. Usage:
  1650. $driver->compare_elements($elem_obj1, $elem_obj2);
  1651. =cut
  1652. sub compare_elements {
  1653. my ( $self, $elem1, $elem2 ) = @_;
  1654. my $res = {
  1655. 'command' => 'elementEquals',
  1656. 'id' => $elem1->{id},
  1657. 'other' => $elem2->{id}
  1658. };
  1659. return $self->_execute_command($res);
  1660. }
  1661. =head2 click
  1662. Description:
  1663. Click any mouse button (at the coordinates set by the last moveto command).
  1664. Input:
  1665. button - any one of 'LEFT'/0 'MIDDLE'/1 'RIGHT'/2
  1666. defaults to 'LEFT'
  1667. Usage:
  1668. $driver->click('LEFT');
  1669. $driver->click(1); #MIDDLE
  1670. $driver->click('RIGHT');
  1671. $driver->click; #Defaults to left
  1672. =cut
  1673. sub click {
  1674. my ( $self, $button ) = @_;
  1675. my $button_enum = { LEFT => 0, MIDDLE => 1, RIGHT => 2 };
  1676. if ( defined $button && $button =~ /(LEFT|MIDDLE|RIGHT)/i ) {
  1677. $button = $button_enum->{ uc $1 };
  1678. }
  1679. elsif ( defined $button && $button =~ /(0|1|2)/ ) {
  1680. $button = $1;
  1681. }
  1682. else {
  1683. $button = 0;
  1684. }
  1685. my $res = { 'command' => 'click' };
  1686. my $params = { 'button' => $button };
  1687. return $self->_execute_command( $res, $params );
  1688. }
  1689. =head2 double_click
  1690. Description:
  1691. Double-clicks at the current mouse coordinates (set by moveto).
  1692. Usage:
  1693. $driver->double_click;
  1694. =cut
  1695. sub double_click {
  1696. my ($self) = @_;
  1697. my $res = { 'command' => 'doubleClick' };
  1698. return $self->_execute_command($res);
  1699. }
  1700. =head2 button_down
  1701. Description:
  1702. Click and hold the left mouse button (at the coordinates set by the
  1703. last moveto command). Note that the next mouse-related command that
  1704. should follow is buttonup . Any other mouse command (such as click
  1705. or another call to buttondown) will yield undefined behaviour.
  1706. Usage:
  1707. $self->button_down;
  1708. =cut
  1709. sub button_down {
  1710. my ($self) = @_;
  1711. my $res = { 'command' => 'buttonDown' };
  1712. return $self->_execute_command($res);
  1713. }
  1714. =head2 button_up
  1715. Description:
  1716. Releases the mouse button previously held (where the mouse is
  1717. currently at). Must be called once for every buttondown command
  1718. issued. See the note in click and buttondown about implications of
  1719. out-of-order commands.
  1720. Usage:
  1721. $self->button_up;
  1722. =cut
  1723. sub button_up {
  1724. my ($self) = @_;
  1725. my $res = { 'command' => 'buttonUp' };
  1726. return $self->_execute_command($res);
  1727. }
  1728. =head2 upload_file
  1729. Description:
  1730. Upload a file from the local machine to the selenium server
  1731. machine. That file then can be used for testing file upload on web
  1732. forms. Returns the remote-server's path to the file.
  1733. Usage:
  1734. my $remote_fname = $driver->upload_file( $fname );
  1735. my $element = $driver->find_element( '//input[@id="file"]' );
  1736. $element->send_keys( $remote_fname );
  1737. =cut
  1738. # this method duplicates upload() method in the
  1739. # org.openqa.selenium.remote.RemoteWebElement java class.
  1740. sub upload_file {
  1741. my ( $self, $filename ) = @_;
  1742. if ( not -r $filename ) { die "upload_file: no such file: $filename"; }
  1743. my $string = ""; # buffer
  1744. zip $filename => \$string
  1745. or die "zip failed: $ZipError\n"; # compress the file into string
  1746. my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
  1747. require MIME::Base64;
  1748. my $params = {
  1749. file => MIME::Base64::encode_base64($string) # base64-encoded string
  1750. };
  1751. return $self->_execute_command( $res, $params );
  1752. }
  1753. =head2 get_text
  1754. Description:
  1755. Get the text of a particular element. Wrapper around L<find_element()>
  1756. Usage:
  1757. $text = $driver->get_text("//div[\@name='q']");
  1758. =cut
  1759. sub get_text {
  1760. my $self = shift;
  1761. return $self->find_element(@_)->get_text();
  1762. }
  1763. =head2 get_body
  1764. Description:
  1765. Get the current text for the whole body. If you want the entire raw HTML instead,
  1766. See L<get_page_source>.
  1767. Usage:
  1768. $body_text = $driver->get_body();
  1769. =cut
  1770. sub get_body {
  1771. my $self = shift;
  1772. return $self->get_text('//body', 'xpath');
  1773. }
  1774. =head2 get_path
  1775. Description:
  1776. Get the path part of the current browser location.
  1777. Usage:
  1778. $path = $driver->get_path();
  1779. =cut
  1780. sub get_path {
  1781. my $self = shift;
  1782. my $location = $self->get_current_url;
  1783. $location =~ s/\?.*//; # strip of query params
  1784. $location =~ s/#.*//; # strip of anchors
  1785. $location =~ s#^https?://[^/]+##; # strip off host
  1786. return $location;
  1787. }
  1788. =head2 set_inner_window_size
  1789. Description:
  1790. Set the inner window size by closing the current window and
  1791. reopening the current page in a new window. This can be useful
  1792. when using browsers to mock as mobile devices.
  1793. This sub will be fired automatically if you set the
  1794. C<inner_window_size> hash key option during instantiation.
  1795. Input:
  1796. INT - height of the window
  1797. INT - width of the window
  1798. Output:
  1799. BOOLEAN - Success or failure
  1800. Usage:
  1801. $driver->set_inner_window_size(640, 480)
  1802. =cut
  1803. sub set_inner_window_size {
  1804. my $self = shift;
  1805. my $height = shift;
  1806. my $width = shift;
  1807. my $location = $self->get_current_url;
  1808. $self->execute_script('window.open("' . $location . '", "_blank")');
  1809. $self->close;
  1810. my @handles = @{ $self->get_window_handles };
  1811. $self->switch_to_window(pop @handles);
  1812. my @resize = (
  1813. 'window.innerHeight = ' . $height,
  1814. 'window.innerWidth = ' . $width,
  1815. 'return 1'
  1816. );
  1817. return $self->execute_script(join(';', @resize)) ? 1 : 0;
  1818. }
  1819. =head2 get_local_storage_item
  1820. Description:
  1821. Get the value of a local storage item specified by the given key.
  1822. Input: 1
  1823. Required:
  1824. STRING - name of the key to be retrieved
  1825. Output:
  1826. STRING - value of the local storage item
  1827. Usage:
  1828. $driver->get_local_storage_item('key')
  1829. =cut
  1830. sub get_local_storage_item {
  1831. my ($self, $key) = @_;
  1832. my $res = { 'command' => 'getLocalStorageItem' };
  1833. my $params = { 'key' => $key };
  1834. return $self->_execute_command($res, $params);
  1835. }
  1836. =head2 delete_local_storage_item
  1837. Description:
  1838. Get the value of a local storage item specified by the given key.
  1839. Input: 1
  1840. Required
  1841. STRING - name of the key to be deleted
  1842. Usage:
  1843. $driver->delete_local_storage_item('key')
  1844. =cut
  1845. sub delete_local_storage_item {
  1846. my ($self, $key) = @_;
  1847. my $res = { 'command' => 'deleteLocalStorageItem' };
  1848. my $params = { 'key' => $key };
  1849. return $self->_execute_command($res, $params);
  1850. }
  1851. 1;
  1852. __END__
  1853. =head1 SEE ALSO
  1854. http://code.google.com/p/selenium/
  1855. https://code.google.com/p/selenium/wiki/JsonWireProtocol#Capabilities_JSON_Object
  1856. https://github.com/gempesaw/Selenium-Remote-Driver/wiki
  1857. Brownie
  1858. Wight
  1859. =cut