Driver.pm 55 KB

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