1
0

Driver.pm 59 KB

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