Driver.pm 52 KB

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