Driver.pm 56 KB

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