Driver.pm 57 KB

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