Driver.pm 61 KB

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