1
0

Driver.pm 55 KB

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