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