Driver.pm 56 KB

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