1
0

Driver.pm 55 KB

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