Driver.pm 56 KB

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