Driver.pm 56 KB

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