Driver.pm 57 KB

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