1
0

Driver.pm 61 KB

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